package com.chinairi.mall.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chinairi.common.annotation.DoPage;
import com.chinairi.common.utils.IdGenerator;
import com.chinairi.common.utils.RedisUtil;
import com.chinairi.common.utils.ResponseUtil;
import com.chinairi.common.utils.UserSession;
import com.chinairi.mall.constant.CiccTableNameEnum;
import com.chinairi.mall.controller.viewobject.*;
import com.chinairi.mall.dao.*;
import com.chinairi.mall.enums.DateLogoEnum;
import com.chinairi.mall.error.BusinessException;
import com.chinairi.mall.error.EmBusinessError;
import com.chinairi.mall.excelParam.*;
import com.chinairi.mall.model.*;
import com.chinairi.mall.service.IOrderInfoService;
import com.chinairi.mall.service.modelobject.*;
import com.chinairi.mall.util.CiccRecordUtil;
import com.chinairi.mall.util.DateUtils;
import com.chinairi.mall.util.NumberFormatUtil;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.nio.charset.Charset;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 订单表,由于order是MYSQL的关键字，所以换名 服务实现类
 * </p>
 *
 * @author gsl
 * @since 2020-09-30
 */
@Service
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements IOrderInfoService {


    @Autowired
    private OrderInfoMapper orderInfoMapper;

    @Autowired
    private OrderGoodsMapper orderGoodsMapper;

    @Autowired
    private OrderServicePurchaseMapper orderServicePurchaseMapper;

    @Autowired
    private OrderServiceTransportMapper orderServiceTransportMapper;

    @Autowired
    private OrderServiceQualityMapper orderServiceQualityMapper;

    @Autowired
    private OrderServiceStorageMapper orderServiceStorageMapper;

    @Autowired
    private OrderServiceSettleMapper orderServiceSettleMapper;

    @Autowired
    private ProjectServiceImpl projectService;

    @Autowired
    private SysUserServiceImpl sysUserService;

    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private ProjectPlanReqDetailMapper projectPlanReqDetailMapper;

    @Autowired
    private OrderServicePurchaseGoodsMapper orderServicePurchaseGoodsMapper;

    @Autowired
    private OrderServiceTransportGoodsMapper orderServiceTransportGoodsMapper;

    @Autowired
    private OrderServiceStorageGoodsMapper orderServiceStorageGoodsMapper;

    @Autowired
    private OrderServiceQualityGoodsMapper orderServiceQualityGoodsMapper;

    @Autowired
    private OrderServiceSettleGoodsMapper orderServiceSettleGoodsMapper;

    @Autowired
    private UserCompanyInfoServiceImpl userCompanyInfoService;

    @Autowired
    private GoodsShoppingCartMapper goodsShoppingCartMapper;

    @Autowired
    private ContractMaitainMapper contractMaitainMapper;

    @Autowired
    private ServiceShelfMapper serviceShelfMapper;


    //服务订单已确认状态
    private static final String SERVICE_ORDER_AGREED_STATE = "2";


    /**
     * 拒绝订单
     *
     * @param orderId
     */
    @Override
    public void refuseOrder(String orderId) {
        OrderInfo orderInfo = orderInfoMapper.selectById(orderId);
        orderInfo.setOrderState("99");
        orderInfoMapper.updateById(orderInfo);
        List<PurchaseDetailAndOrderMO> purchaseDetailAndOrderMoList = orderInfoMapper.getPurchaseListByOrderId(orderId);
        if (purchaseDetailAndOrderMoList.size() > 0) {
            projectPlanReqDetailMapper.batchUpdate(purchaseDetailAndOrderMoList.stream().peek((list) -> {
                float goodsNumber = list.getOgGoodsNumber();
                list.setPlanReqNumNow(list.getPlanReqNumNow() + goodsNumber);
                list.setPlanAlreadyBuyNum(list.getPlanAlreadyBuyNum() - goodsNumber);
                list.setPlanShouldBuyNum(list.getPlanShouldBuyNum() + goodsNumber);
            }).collect(Collectors.toList()));
        }
        orderInfoMapper.updatePurchaseOrderState(orderId, "99");
        orderInfoMapper.updateTransportOrderState(orderId, "99");
        orderInfoMapper.updateStorageOrderState(orderId, "99");
        orderInfoMapper.updateQualityOrderState(orderId, "99");
        orderInfoMapper.updateSettleOrderState(orderId, "99");
    }

    /**
     * 生成订单
     *
     * @param orderInfoVO
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public OrderInfoVO addOrder(OrderInfoVO orderInfoVO) {

        //服务分类的标志位
        Map<String, Integer> flagMap = new HashMap<>(12);
        flagMap.put("fwfl005", 0);
        flagMap.put("fwfl006", 1);
        flagMap.put("fwfl007", 0);
        flagMap.put("fwfl008", 0);
        flagMap.put("fwfl009", 0);
        flagMap.put("fwfl010", 0);
        flagMap.put("fwfl011", 1);
        flagMap.put("fwfl012", 1);
        flagMap.put("fwfl013", 1);
        flagMap.put("fwfl016", 0);
        flagMap.put("fwfl017", 0);
        flagMap.put("fwfl018", 0);

        //主订单
        String orderId = NumberFormatUtil.numberFormat(6, orderInfoMapper.getOrderNo());
        orderInfoVO.setOrderId(orderId);
        orderInfoVO.setOrderTime(new Date());
        orderInfoVO.setOrderState("1");
        orderInfoVO.setOrderPurchaseDepartment(UserSession.getOrgId());
        orderInfoVO.setCreateUserId(UserSession.getUserId());
        orderInfoVO.setCreateUser(UserSession.getLoginName());
        orderInfoVO.setCreateTime(new Date());
        String contractId = orderInfoMapper.selectContractId(orderInfoVO.getOrderShopId());
        if (contractId != null) {
            orderInfoVO.setOrderContractId(contractId);
        }
//        //发货地址
//        String addressType = "1";
//        ReSeAddress reSeAddress = orderInfoMapper.selectReSeAddress(orderInfoVO.getOrderShopId(), addressType);
//        if (reSeAddress != null) {
//            orderInfoVO.setOrderSupplierMan(reSeAddress.getRsaMan());
//            orderInfoVO.setOrderSupplierPhone(reSeAddress.getRsaPhone());
//        }
        ShopInfoToCompRedisMO shopInfoToCompRedisMO = userCompanyInfoService.getShopInfoToCompFromRedis(orderInfoVO.getOrderShopId());
        if (shopInfoToCompRedisMO != null) {
            orderInfoVO.setOrderSupplierId(shopInfoToCompRedisMO.getUciDbid());
            orderInfoVO.setOrderSupplierName(shopInfoToCompRedisMO.getUciCompName());
            orderInfoVO.setOrderSupplierMan(shopInfoToCompRedisMO.getUciRepresentative());
            orderInfoVO.setOrderSupplierPhone(shopInfoToCompRedisMO.getUciTelphone() != null ? shopInfoToCompRedisMO.getUciTelphone() : "供应商未填写");
            orderInfoVO.setOrderSendAddress(shopInfoToCompRedisMO.getUciBusinessAddress());
        }
        PurchaseToProjectRedisMO purchaseToProjectRedisMO = projectService.getPurchaseToProjectFromRedis(orderInfoVO.getPlanPurchaseId());
        if (purchaseToProjectRedisMO != null) {
            orderInfoVO.setOrderName(purchaseToProjectRedisMO.getpCompany() + "-" + purchaseToProjectRedisMO.getpName() + "-实物商品订单");
            orderInfoVO.setOrderProjectId(purchaseToProjectRedisMO.getpId());
            orderInfoVO.setOrderProjectName(purchaseToProjectRedisMO.getpName());
        }
        UserInfoToRedisMO userInfoToRedisMO = sysUserService.getUserInfoFromRedis(UserSession.getUserId());
        String uciName = "";
        if (userInfoToRedisMO != null) {
            uciName = (String) userCompanyInfoService.getCompMapFromRedis(userInfoToRedisMO.getUciDbid());
        }
        String userPhone = "";
        if (userInfoToRedisMO != null) {
            userPhone = userInfoToRedisMO.getUserMobile();
            orderInfoVO.setOrderPurchaseMan(userInfoToRedisMO.getUserRealNm());
            orderInfoVO.setOrderPurchasePhone(userPhone);
            orderInfoVO.setOrderUserCode(userInfoToRedisMO.getUciDbid());
            orderInfoVO.setOrderPurchaseComName(uciName);
        }
        //收货地址
        String receiveAddress;
        receiveAddress = orderInfoMapper.selectReceiveAddress(UserSession.getUserId());
        if (receiveAddress == null && orderInfoVO.getOrderServiceTransportVO() == null) {
            throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR, "没有默认收获地址！  请选择 [配送服务] 或前往 [个人中心] 中设置地址");
        }
        orderInfoVO.setOrderReceiveAddress(receiveAddress);
        BigDecimal orderGoodsMoney = new BigDecimal(0);
        //结算点
        String settlePoint;
        if (orderInfoVO.getOrderServiceSettleVO() != null) {
            settlePoint = orderInfoVO.getOrderServiceSettleVO().getOsseType() == "fwfl014" ? "非代储（入库）结算" : "代储（出库）结算";
        } else {
            //如果没有选择，则默认
            settlePoint = "非代储（入库）结算";
        }
        Map<String, Date> planPurchaseDetailMap = new HashMap<>(16);
        List<String> goodsDbIdList = getGoodsDbIdList(orderInfoVO.getOrderGoodsList());
        List<ProjectPlanReqDetailMO> projectPlanReqDetailMOList = orderInfoMapper.selectPlanReqDetail(orderInfoVO.getPlanPurchaseId(), goodsDbIdList);
        for (ProjectPlanReqDetailMO projectPlanReqDetailMO : projectPlanReqDetailMOList) {
            if (projectPlanReqDetailMO.getPlanArrivalTime() != null) {
                planPurchaseDetailMap.put(projectPlanReqDetailMO.getGoodsDbid(), projectPlanReqDetailMO.getPlanArrivalTime());
            }
            if (projectPlanReqDetailMO.getPlanArrivalAddress() != null) {
                orderInfoVO.setOrderReceiveAddress(projectPlanReqDetailMO.getPlanArrivalAddress());
            }
        }
        //配送的收货地址
        if (orderInfoVO.getOrderServiceTransportVO() != null) {
            orderInfoVO.setOrderReceiveAddress(orderInfoVO.getOrderServiceTransportVO().getOstContractAddress());
            OrderServiceTransportVO  orderServiceTransportVO =   orderInfoVO.getOrderServiceTransportVO();
            orderServiceTransportVO.setCarriageAddress(orderInfoMapper.getBussinessAdress(orderServiceTransportVO.getOstShopId()));


        }
        //订单中实物商品list
        List<OrderGoods> orderGoodsList = orderInfoVO.getOrderGoodsList();
        for (OrderGoods orderGoods : orderGoodsList) {
            orderGoods.setOgId(IdGenerator.UUID());
            orderGoods.setOrderId(orderId);
            orderGoods.setOgSettlePoint(settlePoint);
            orderGoods.setOgDeliveryData(planPurchaseDetailMap.get(orderGoods.getGoodsDbid()));
            orderGoods.setCreateUser(UserSession.getUserId());
            orderGoods.setCreateTime(new Date());
        }

        //生成采购服务订单
        if (orderInfoVO.getOrderServicePurchaseVO() != null) {
            OrderServicePurchaseVO orderServicePurchaseVO = addOrderServicePurchase(orderInfoVO, orderId, userPhone);
            orderInfoVO.setOrderServicePurchaseVO(orderServicePurchaseVO);
        }
        //生成配送服务订单
        if (orderInfoVO.getOrderServiceTransportVO() != null) {
            OrderServiceTransportVO orderServiceTransportVO = addOrderServiceTransport(orderInfoVO, orderId, userPhone, flagMap);
            orderInfoVO.setOrderServiceTransportVO(orderServiceTransportVO);
        }
        //生成质控服务订单
        if (orderInfoVO.getOrderServiceQualityVOList() != null) {
            List<OrderServiceQualityVO> orderServiceQualityVOList = addOrderServiceQuality(orderInfoVO, orderId, userPhone, flagMap);
            orderInfoVO.setOrderServiceQualityVOList(orderServiceQualityVOList);
        }
        //生成仓储服务订单
        if (orderInfoVO.getOrderServiceStorageVOList() != null) {
            List<OrderServiceStorageVO> orderServiceStorageVOList = addOrderServiceStorage(orderInfoVO, orderId, userPhone, flagMap);
            orderInfoVO.setOrderServiceStorageVOList(orderServiceStorageVOList);
        }
        //生成结算服务订单
        if (orderInfoVO.getOrderServiceSettleVO() != null) {
            OrderServiceSettleVO orderServiceSettleVO = addOrderServiceSettle(orderInfoVO, orderId, userPhone, purchaseToProjectRedisMO);
            orderInfoVO.setOrderServiceSettleVO(orderServiceSettleVO);
        }
        return orderInfoVO;
    }

    /**
     * 订单确认
     *
     * @param orderInfoVO
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void confirmOrder(OrderInfoVO orderInfoVO, List<String> scIdList) {
        //生成商品主订单
        String orderId = NumberFormatUtil.numberFormat(6, orderInfoMapper.getOrderNo());
        orderInfoVO.setOrderId(orderId);
        orderInfoMapper.insert(orderInfoVO);
        //生成订单下的商品
        orderGoodsMapper.batchInsert(orderInfoVO.getOrderGoodsList().stream().peek((item) -> item.setOrderId(orderId)).collect(Collectors.toList()));
        //下单后更新采购计划详情的数据
        updatePlanPurchaseNum(orderInfoVO);
        //下单后更新商品库存、可供采购量和销量
        updateGoodsInfoNum(orderInfoVO.getOrderGoodsList());
        //生成采购服务订单
        if (orderInfoVO.getOrderServicePurchaseVO() != null) {
            String ospId = NumberFormatUtil.numberFormat(6, orderInfoMapper.getOrderPurchaseNo());
            orderInfoVO.getOrderServicePurchaseVO().setOspId(ospId);
            orderServicePurchaseMapper.insert(orderInfoVO.getOrderServicePurchaseVO());
            orderInfoMapper.batchInsertServicePurchaseGoods(orderInfoVO.getOrderServicePurchaseVO().getOrderServicePurchaseGoodsList().stream().peek((item) -> item.setOspId(ospId)).collect(Collectors.toList()));
        }
        //生成配送服务订单
        if (orderInfoVO.getOrderServiceTransportVO() != null) {
            String ostId = NumberFormatUtil.numberFormat(6, orderInfoMapper.getOrderTransportNo());
            orderInfoVO.getOrderServiceTransportVO().setOstId(ostId);
            orderInfoVO.getOrderServicePurchaseVO().setOrderId(orderId);
            orderServiceTransportMapper.insert(orderInfoVO.getOrderServiceTransportVO());
            orderInfoMapper.batchInsertServiceTransportGoods(orderInfoVO.getOrderServiceTransportVO().getOrderServiceTransportGoodsList().stream().peek((item) -> item.setOstId(ostId)).collect(Collectors.toList()));
        }
        //生成质控服务订单
        if (orderInfoVO.getOrderServiceQualityVOList() != null) {
            for (OrderServiceQualityVO orderServiceQualityVO : orderInfoVO.getOrderServiceQualityVOList()) {
                String osqId = NumberFormatUtil.numberFormat(6, orderInfoMapper.getOrderQualityNo());
                orderServiceQualityVO.setOsqId(osqId);
                orderServiceQualityVO.setOrderId(orderId);
                orderServiceQualityMapper.insert(orderServiceQualityVO);
                orderInfoMapper.batchInsertServiceQualityGoods(orderServiceQualityVO.getOrderServiceQualityGoodsList().stream().peek((item) -> item.setOsqId(osqId)).collect(Collectors.toList()));
            }
        }
        //生成仓储服务订单
        if (orderInfoVO.getOrderServiceStorageVOList() != null) {
            for (OrderServiceStorageVO orderServiceStorageVO : orderInfoVO.getOrderServiceStorageVOList()) {
                String ossId = NumberFormatUtil.numberFormat(6, orderInfoMapper.getOrderStorageNo());
                orderServiceStorageVO.setOssId(ossId);
                orderServiceStorageVO.setOrderId(orderId);
                orderServiceStorageMapper.insert(orderServiceStorageVO);
                orderInfoMapper.batchInsertServiceStorageGoods(orderServiceStorageVO.getOrderServiceStorageGoodsList().stream().peek((item) -> item.setOssId(ossId)).collect(Collectors.toList()));
            }
        }
        //生成结算服务订单
        if (orderInfoVO.getOrderServiceSettleVO() != null) {
            String osseId = NumberFormatUtil.numberFormat(6, orderInfoMapper.getOrderSettleNo());
            orderInfoVO.getOrderServiceSettleVO().setOsseId(osseId);
            orderInfoVO.getOrderServiceSettleVO().setOrderId(orderId);
            orderServiceSettleMapper.insert(orderInfoVO.getOrderServiceSettleVO());
            orderInfoMapper.batchInsertServiceSettleGoods(orderInfoVO.getOrderServiceSettleVO().getOrderServiceSettleGoodsList().stream().peek((item) -> item.setOsseId(osseId)).collect(Collectors.toList()));
        }
        //删除购物车中的商品
        goodsShoppingCartMapper.deleteBatchIds(scIdList);
//        //下单后调用改接口发送订单信息，httpUrl是调用的接口的请求地址，必须是http请求链接，目前暂时置空，后面根据供应商短项目部署的环境填写不同的请求链接
        Map<String, Object> map = new HashMap<>();
        try {
            map = sendToProvider(orderInfoVO);
        } catch (Exception e) {
            e.printStackTrace();
            ResponseUtil.toWarningMessage("订单确认失败", false);
        }
        if (!map.containsValue("success")) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            ResponseUtil.toWarningMessage("订单确认失败", false);
        }
    }

    /**
     * 供李昌赐使用
     * 下单后发送订单信息
     *
     * @param orderInfoVO
     */
    @Override
    public Map<String, Object> sendToProvider(OrderInfoVO orderInfoVO) throws Exception {
        Map<String, Object> map = new HashMap<>();
        //订单编号
        map.put("orderNo", orderInfoVO.getOrderId());
        //合同编号
        map.put("contractNo", orderInfoVO.getOrderContractId());
        //订单日期
        map.put("orderDate", DateUtils.getDate("yyyy-MM-dd", orderInfoVO.getOrderTime()));
        //供应商负责人
        map.put("seller", orderInfoVO.getOrderSupplierMan());
        //负责人电话
        map.put("telephone", orderInfoVO.getOrderSupplierPhone());
        //交货地址
        map.put("receiveAddress", orderInfoVO.getOrderReceiveAddress());
        //采购商名称
        map.put("userOrgNM", orderInfoVO.getOrderPurchaseComName());
        //订单名称
        map.put("orderName", orderInfoVO.getOrderName());
        //项目名称
        map.put("projectName", orderInfoVO.getOrderProjectName());
        //采购商联系人
        map.put("purchaseUser", orderInfoVO.getOrderPurchaseMan());
        //采购商联系人电话
        map.put("purchasePhone", orderInfoVO.getOrderPurchasePhone());
        List<OrderGoods> orderGoodsList = orderInfoVO.getOrderGoodsList();
        List<Map<String, Object>> purOderMatModelList = null;
        Map<String, Object> purOderMatModel = null;
        if (null != orderGoodsList && !orderGoodsList.isEmpty()) {
            purOderMatModelList = new ArrayList<>();
            for (OrderGoods orderGoods : orderGoodsList) {
                purOderMatModel = new HashMap<>();
                String goodsDbId = orderGoods.getGoodsDbid();
                Map<String, Object> goodsInfo = orderInfoMapper.getGoodsInfo(goodsDbId);
                purOderMatModel.put("deliveryDate", DateUtils.getDate("yyyy-MM-dd", orderGoods.getOgDeliveryData()));
                purOderMatModel.put("matName", goodsInfo.get("matName"));
                purOderMatModel.put("Texture", goodsInfo.get("Texture"));
                purOderMatModel.put("unit", goodsInfo.get("unit"));
                purOderMatModel.put("technologyStandard", goodsInfo.get("technologyStandard"));
                purOderMatModel.put("count", orderGoods.getOgGoodsNumber());
                purOderMatModel.put("price", orderGoods.getOgGoodsPrice());
                purOderMatModel.put("amount", orderGoods.getOgGoodsMoney());
                purOderMatModel.put("settleType", orderGoods.getOgSettlePoint());
                purOderMatModel.put("supervisionLevel", "");
                purOderMatModel.put("remark", "");
                purOderMatModel.put("custMatCode", goodsInfo.get("matCode"));
                purOderMatModelList.add(purOderMatModel);
            }
        } else {
            new ArrayList<>();
        }
        map.put("purOderMatModelList", purOderMatModelList);
        Map<String, Object> result = new HashMap<>();
        String url = orderInfoMapper.getOrderSendUrl();
        HttpClient httpClient = HttpClientBuilder.create().build();
        HttpPost httpPost = new HttpPost(url);
        httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json;charset=utf-8");
        httpPost.addHeader("Content-type", "application/json; charset=utf-8");
        httpPost.setHeader("Accept", "application/json");
        httpPost.setEntity(new StringEntity(JSON.toJSONString(map), Charset.forName("UTF-8")));
        HttpResponse response = httpClient.execute(httpPost);
        if (null == response || response.getStatusLine() == null) {
            throw new Exception("Post Request For Url[{}] is not ok. Response is null");
        } else if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            throw new Exception("Post Request For Url[{}] is not ok. Response Status Code is {" + response.getStatusLine().getStatusCode() + "}");
        }
        String resultString = EntityUtils.toString(response.getEntity());
        JSONObject jsonObj = JSONObject.parseObject(resultString);
        if ("SUCCESS".equals(jsonObj.getString("STATUS"))) {
            result.put("STATUS", "success");
        } else {
            result.put("STATUS", "failed");
        }
        result.put("MESSAGE", jsonObj.getString("MSG"));
        return result;
    }


    /**
     * 更新商品库存和销量
     *
     * @param orderGoodsList
     */
    private void updateGoodsInfoNum(List<OrderGoods> orderGoodsList) {
        //传过来的商品数量
        Map<String, Float> orderGoodsNumMap = getOrderGoodsNum(orderGoodsList);
        List<GoodsInfo> goodsInfoList = getGoodsInfoListByDbId(orderGoodsList);
        orderGoodsMapper.batchUpdateGoodsNum(goodsInfoList.stream().peek((list) -> {
            list.setGoodsCanBuy(list.getGoodsCanBuy() != null ? (list.getGoodsCanBuy() - orderGoodsNumMap.get(list.getGoodsDbid()) > 0 ? list.getGoodsCanBuy() - orderGoodsNumMap.get(list.getGoodsDbid()) : 0) : 0);
            list.setGoodsStock(list.getGoodsStock() != null ? (list.getGoodsStock() - orderGoodsNumMap.get(list.getGoodsDbid()) > 0 ? list.getGoodsStock() - orderGoodsNumMap.get(list.getGoodsDbid()) : 0) : 0);
            list.setGoodsSold(list.getGoodsSold() != null ? (list.getGoodsSold() + orderGoodsNumMap.get(list.getGoodsDbid())) : 0);
        }).collect(Collectors.toList()));

    }

    /**
     * 根据商品ID list获取商品信息
     *
     * @param orderGoodsList
     * @return
     */
    private List<GoodsInfo> getGoodsInfoListByDbId(List<OrderGoods> orderGoodsList) {
        List<String> goodsDbIdList = getGoodsDbIdList(orderGoodsList);
        return orderGoodsMapper.selectGoodsNum(goodsDbIdList);
    }

    /**
     * 下单后更新采购计划数据
     *
     * @param orderInfoVO
     */
    @Transactional(rollbackFor = Exception.class)
    protected void updatePlanPurchaseNum(OrderInfoVO orderInfoVO) {
        List<String> goodsDbIdList = getGoodsDbIdList(orderInfoVO.getOrderGoodsList());
        Map<String, Float> orderGoodsNum = getOrderGoodsNum(orderInfoVO.getOrderGoodsList());
        List<ProjectPlanReqDetailMO> projectPlanReqDetailMOList = orderInfoMapper.selectPlanReqDetail(orderInfoVO.getPlanPurchaseId(), goodsDbIdList);
        if (projectPlanReqDetailMOList.size() > 0) {
            orderInfoMapper.batchUpdateReqDetailNum(projectPlanReqDetailMOList.stream().peek((list) -> {
                list.setPlanReqNumNow(list.getPlanReqNumNow() != null ? (list.getPlanReqNumNow() - orderGoodsNum.get(list.getGoodsDbid()) > 0 ? list.getPlanReqNumNow() - orderGoodsNum.get(list.getGoodsDbid()) : 0) : 0);
                list.setPlanAlreadyBuyNum(list.getPlanAlreadyBuyNum() != null ? (list.getPlanAlreadyBuyNum() + orderGoodsNum.get(list.getGoodsDbid())) : 0);
                list.setPlanShouldBuyNum(list.getPlanShouldBuyNum() != null ? (list.getPlanShouldBuyNum() - orderGoodsNum.get(list.getGoodsDbid()) > 0 ? list.getPlanShouldBuyNum() - orderGoodsNum.get(list.getGoodsDbid()) : 0) : 0);
            }).collect(Collectors.toList()));
        }
    }

    /**
     * 获取商品数量
     *
     * @param orderGoodsList
     * @return
     */
    private Map<String, Float> getOrderGoodsNum(List<OrderGoods> orderGoodsList) {
        Map<String, Float> orderGoodsNum = new HashMap<>(orderGoodsList.size());
        for (OrderGoods orderGoods : orderGoodsList) {
            orderGoodsNum.put(orderGoods.getGoodsDbid(), orderGoods.getOgGoodsNumber());
        }
        return orderGoodsNum;
    }


    /**
     * 获取商品ID List
     *
     * @param orderGoodsList
     * @return
     */
    private List<String> getGoodsDbIdList(List<OrderGoods> orderGoodsList) {
        //商品的id
        List<String> goodsDbIdList = new ArrayList<>();
        for (OrderGoods orderGoods : orderGoodsList) {
            goodsDbIdList.add(orderGoods.getGoodsDbid());
        }
        return goodsDbIdList;
    }

    /**
     * 生成采购服务订单
     *
     * @param orderInfoVO 前端传入的
     * @param orderId     商品订单ID
     * @param userPhone   下单人联系电话
     * @return
     */
    private OrderServicePurchaseVO addOrderServicePurchase(OrderInfoVO orderInfoVO, String orderId, String userPhone) {
        //采购服务订单
        OrderServicePurchaseVO orderServicePurchaseVO = orderInfoVO.getOrderServicePurchaseVO();
        //订单中实物商品list
        List<OrderGoods> orderGoodsList = orderInfoVO.getOrderGoodsList();
//        String ospId = NumberFormatUtil.numberFormat(6, orderInfoMapper.getOrderPurchaseNo());
//        orderServicePurchaseVO.setOspId(ospId);
        orderServicePurchaseVO.setOrderId(orderId);
        orderServicePurchaseVO.setOspPurchaseType("标准目录采购");
        PurchaseToProjectRedisMO purchaseToProjectRedisMO = projectService.getPurchaseToProjectFromRedis(orderInfoVO.getPlanPurchaseId());
        if (purchaseToProjectRedisMO != null) {
            orderServicePurchaseVO.setOspName(purchaseToProjectRedisMO.getpCompany() + "-" + purchaseToProjectRedisMO.getpName() + "-采购服务订单");
        }
        orderServicePurchaseVO.setOspState("0");
        CompShop compShop = orderInfoMapper.selectPurchaseShop();
        if (compShop == null) {
            throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR, "没有采购服务店铺，无法下单");
        }
        orderServicePurchaseVO.setOspShopId(compShop.getCsDbid());
        Map<Object, Object> shopMap = redisUtil.hmget("shopInfoMap");
        if (!redisUtil.hasKey("shopInfoMap") || shopMap.size() == 0 || redisUtil.hmget("shopInfoMap").get(compShop.getCsDbid()) != null) {
            userCompanyInfoService.putShopInfoToRedis();
        }
        ShopInfoToCompRedisMO shopInfoToCompRedisMO = (ShopInfoToCompRedisMO) redisUtil.hmget("shopInfoMap").get(compShop.getCsDbid());
        if (shopInfoToCompRedisMO != null) {
            orderServicePurchaseVO.setOspPurchaseUnit(shopInfoToCompRedisMO.getCsShopName());
            orderServicePurchaseVO.setOspContactsMan(shopInfoToCompRedisMO.getUciRepresentative());
            orderServicePurchaseVO.setOspContactsManPhone(shopInfoToCompRedisMO.getUciTelphone());
            orderServicePurchaseVO.setOspPurchaseUnitAddress(shopInfoToCompRedisMO.getUciBusinessAddress());
        }
        orderServicePurchaseVO.setCreateUserId(UserSession.getUserId());
        orderServicePurchaseVO.setCreateUser(UserSession.getUserName());
        orderServicePurchaseVO.setCreateUserPhone(userPhone);
        orderServicePurchaseVO.setCreateTime(new Date());
        //收货地址
        String receiveAddress;
        receiveAddress = orderInfoMapper.selectReceiveAddress(UserSession.getUserId());
        if (orderInfoVO.getOrderServiceTransportVO() != null) {
            receiveAddress = orderInfoVO.getOrderServiceTransportVO().getOstContractAddress();
        }
        //交货期
        Map<String, Date> planPurchaseDetailMap = new HashMap<>(16);
        List<String> goodsDbIdList = getGoodsDbIdList(orderInfoVO.getOrderGoodsList());
        List<ProjectPlanReqDetailMO> projectPlanReqDetailMOList = orderInfoMapper.selectPlanReqDetail(orderInfoVO.getPlanPurchaseId(), goodsDbIdList);
        for (ProjectPlanReqDetailMO projectPlanReqDetailMO : projectPlanReqDetailMOList) {
            if (projectPlanReqDetailMO.getPlanArrivalTime() != null) {
                planPurchaseDetailMap.put(projectPlanReqDetailMO.getGoodsDbid(), projectPlanReqDetailMO.getPlanArrivalTime());
            }
        }
        //采购计划中实物商品list
        List<OrderServicePurchaseGoods> orderServicePurchaseGoodsList = new ArrayList<>();
        List<GoodsInfo> goodsInfoList = getGoodsInfoListByDbId(orderGoodsList);
        Map<String, GoodsInfo> goodsInfoMap = new HashMap<>(goodsInfoList.size());
        for (GoodsInfo goodsInfo : goodsInfoList) {
            goodsInfoMap.put(goodsInfo.getGoodsDbid(), goodsInfo);
        }
        for (OrderGoods orderGoods : orderGoodsList) {
            //将商品信息同步到采购服务订单下的商品表中
            OrderServicePurchaseGoods orderServicePurchaseGoods = new OrderServicePurchaseGoods();
            orderServicePurchaseGoods.setOspgId(IdGenerator.UUID());
            orderServicePurchaseGoods.setOspgGoodsDbid(orderGoods.getGoodsDbid());
            orderServicePurchaseGoods.setOspgGoodsName(orderGoods.getGoodsName());
            orderServicePurchaseGoods.setOspgOrderId(orderId);
            //供应商名称
            orderServicePurchaseGoods.setOspgUciName(orderInfoVO.getOrderShopName());
            orderServicePurchaseGoods.setOspgGoodsNumber(orderGoods.getOgGoodsNumber());
            orderServicePurchaseGoods.setOspgGoodsUnit(orderGoods.getOgGoodsUnit());
            if (goodsInfoMap.get(orderGoods.getGoodsDbid()).getGoodsGoodsWeight() != null) {
                orderServicePurchaseGoods.setOspgGoodsSingleWeight(goodsInfoMap.get(orderGoods.getGoodsDbid()).getGoodsGoodsWeight().doubleValue());
            }
            orderServicePurchaseGoods.setOspgGoodsPrice(orderGoods.getOgGoodsPrice());
            orderServicePurchaseGoods.setOspgGoodsClass("框架产品");
            orderServicePurchaseGoods.setOspgValuationUnit("采购金额百分比");
            orderServicePurchaseGoods.setOspgProcurementCycle("12个月");
            //服务计价单价
            BigDecimal valuationPrice = BigDecimal.valueOf(0.025);
            orderServicePurchaseGoods.setOspgValuationPrice(valuationPrice);
            //商品采购金额
            BigDecimal goodsMoney = orderGoods.getOgGoodsPrice().multiply(BigDecimal.valueOf(orderGoods.getOgGoodsNumber()));
            orderServicePurchaseGoods.setOspgGoodsMoney(goodsMoney);
            //服务收费金额
            orderServicePurchaseGoods.setOspgGoodsServiceMoney(goodsMoney.multiply(valuationPrice));
            orderServicePurchaseGoods.setCreateUser(UserSession.getUserId());
            orderServicePurchaseGoods.setCreateTime(new Date());
            orderServicePurchaseGoods.setOspgArrivalAddress(receiveAddress);
            orderServicePurchaseGoods.setOspgArrivalTime(planPurchaseDetailMap.get(orderServicePurchaseGoods.getOspgGoodsDbid()));
            orderServicePurchaseGoodsList.add(orderServicePurchaseGoods);
        }
        orderServicePurchaseVO.setOrderServicePurchaseGoodsList(orderServicePurchaseGoodsList);
        //获取采购服务详情
        QueryWrapper<ServiceShelf> serviceShelfQueryWrapper=new QueryWrapper<>();
        serviceShelfQueryWrapper.eq("SS_SERVICE_CLASS_NAME",orderServicePurchaseVO.getOspPurchaseType());
        ServiceShelf serviceShelf=serviceShelfMapper.selectOne(serviceShelfQueryWrapper);
        orderServicePurchaseVO.setPhone(serviceShelf.getSsPhone());
        orderServicePurchaseVO.setPerson(serviceShelf.getSsPerson());
        return orderServicePurchaseVO;
    }

    /**
     * 生成配送服务订单
     *
     * @param orderInfoVO 订单信息
     * @param orderId     实物订单编号
     * @param userPhone   用户电话
     * @param flagMap     服务标志位
     */
    private OrderServiceTransportVO addOrderServiceTransport(OrderInfoVO orderInfoVO, String orderId, String userPhone, Map<String, Integer> flagMap) {
        //从前端接收过来的配送服务主表信息
        OrderServiceTransportVO orderServiceTransportVO = orderInfoVO.getOrderServiceTransportVO();
//        String ostId = NumberFormatUtil.numberFormat(6, orderInfoMapper.getOrderTransportNo());
        orderServiceTransportVO.setOrderId(orderId);
//        orderServiceTransportVO.setOstId(ostId);
        Map<Object, Object> shopMap = redisUtil.hmget("shopInfoMap");
        if (!redisUtil.hasKey("shopInfoMap") || shopMap.size() == 0 || redisUtil.hmget("shopInfoMap").get(orderServiceTransportVO.getOstShopId()) != null) {
            userCompanyInfoService.putShopInfoToRedis();
        }
        ShopInfoToCompRedisMO shopInfoToCompRedisMO = (ShopInfoToCompRedisMO) redisUtil.hmget("shopInfoMap").get(orderServiceTransportVO.getOstShopId());
        if (shopInfoToCompRedisMO != null) {
            orderServiceTransportVO.setOstTransportUnit(shopInfoToCompRedisMO.getCsShopName());
            orderServiceTransportVO.setOstContractMan(shopInfoToCompRedisMO.getUciRepresentative());
            orderServiceTransportVO.setOstContractManPhone(shopInfoToCompRedisMO.getUciTelphone());
        }
        orderServiceTransportVO.setOstState("0");
        orderServiceTransportVO.setCreateUserPhone(userPhone);
        orderServiceTransportVO.setCreateUser(UserSession.getUserName());
        orderServiceTransportVO.setCreateTime(new Date());
        PurchaseToProjectRedisMO purchaseToProjectRedisMO = projectService.getPurchaseToProjectFromRedis(orderInfoVO.getPlanPurchaseId());
        if (purchaseToProjectRedisMO != null) {
            orderServiceTransportVO.setOstName(purchaseToProjectRedisMO.getpCompany() + "-" + purchaseToProjectRedisMO.getpName() + "-配送服务订单");
        }
        //订单中实物商品list
        List<OrderGoods> orderGoodsList = orderInfoVO.getOrderGoodsList();
        //获取商品的物料ID列表
        List<String> goodsDbIdList = getGoodsDbIdList(orderGoodsList);
        //传过来的服务分类
        String serviceClass = orderServiceTransportVO.getOstTransportType();
        //查询商品服务
        List<MatServiceClassMO> matServiceClassMOList = orderGoodsMapper.selectGoodsServiceClass(
                goodsDbIdList,
                serviceClass,
                flagMap.get(serviceClass),
                orderServiceTransportVO.getOstShopId());
        Map<String, MatServiceClassMO> matServiceClassMOMap = new HashMap<>(orderGoodsList.size());
        if (matServiceClassMOList.size() > 0) {
            for (MatServiceClassMO matServiceClassMO : matServiceClassMOList) {
                matServiceClassMOMap.put(matServiceClassMO.getGoodsDbid(), matServiceClassMO);
            }
        }

        Map<Object, Object> shopMap2 = redisUtil.hmget("shopInfoMap");
        if (!redisUtil.hasKey("shopInfoMap") || shopMap2.size() == 0 || redisUtil.hmget("shopInfoMap").get(orderInfoVO.getOrderShopId()) != null) {
            userCompanyInfoService.putShopInfoToRedis();
        }
        ShopInfoToCompRedisMO shopInfoToCompRedisMO2 = (ShopInfoToCompRedisMO) redisUtil.hmget("shopInfoMap").get(orderInfoVO.getOrderShopId());

        //配送服务中实物商品list
        List<OrderServiceTransportGoods> orderServiceTransportGoodsList = new ArrayList<>();
        for (OrderGoods orderGoods : orderInfoVO.getOrderGoodsList()) {
            //配送服务
            OrderServiceTransportGoods orderServiceTransportGoods = new OrderServiceTransportGoods();
            orderServiceTransportGoods.setOstgId(IdGenerator.UUID());
            //绑定配送服务主表
//            orderServiceTransportGoods.setOstId(ostId);
            orderServiceTransportGoods.setOstgGoodsDbid(orderGoods.getGoodsDbid());
            orderServiceTransportGoods.setOstgGoodsName(orderGoods.getGoodsName());
            orderServiceTransportGoods.setOstgOrderId(orderId);
            orderServiceTransportGoods.setOstgGoodsNumber(orderGoods.getOgGoodsNumber());
            orderServiceTransportGoods.setOstgGoodsUnit(orderGoods.getOgGoodsUnit());
            orderServiceTransportGoods.setOstgGoodsPrice(orderGoods.getOgGoodsPrice());
            orderServiceTransportGoods.setOstgGoodsMoney(orderGoods.getOgGoodsMoney());
            orderServiceTransportGoods.setOstgEstimateDay(orderServiceTransportVO.getOstgEstimateDay());
            if (shopInfoToCompRedisMO != null) {
                orderServiceTransportGoods.setOstgUciName(shopInfoToCompRedisMO2.getCsShopName());
                orderServiceTransportGoods.setOstgDeliveryAddress(shopInfoToCompRedisMO2.getUciBusinessAddress());
            }
            orderServiceTransportGoods.setOstgReceiveAddress(orderServiceTransportVO.getOstContractAddress());
            Random random = new Random();
            orderServiceTransportGoods.setOstgRegularCoefficient("[" + random.nextInt(2) + "," + random.nextInt(2) + "," + random.nextInt(2) + "]");
            orderServiceTransportGoods.setOstgBigCoefficient("1.1");
            orderServiceTransportGoods.setOstgAntisepticCoefficient("1.03");
            orderServiceTransportGoods.setOstgLongDistanceCoefficient(Float.valueOf("0.85"));
            MatServiceClassMO matServiceClassMO = matServiceClassMOMap.get(orderGoods.getGoodsDbid());
            //开始放入商品分类
            if (matServiceClassMOMap.size() > 0 && matServiceClassMO != null) {
                orderServiceTransportGoods.setOstgValuationUnit(matServiceClassMO.getSpPriceUnit() != null ? matServiceClassMO.getSpPriceUnit() : "");
//                orderServiceTransportGoods.setOstgTransportPrice(matServiceClassMO.getSpServiceCharge() != null ? matServiceClassMO.getSpServiceCharge() : BigDecimal.valueOf(0));
                orderServiceTransportGoods.setOstgTransportPrice(BigDecimal.valueOf(1.06));
                orderServiceTransportGoods.setOstgGoodsClass(matServiceClassMO.getGoodsClass() != null ? matServiceClassMO.getGoodsClass() : "");
                orderServiceTransportGoods.setOstgGoodsSingleWeight(matServiceClassMO.getGoodsGoodsWeight().floatValue());
            }
            orderServiceTransportGoods.setCreateUser(UserSession.getUserId());
            orderServiceTransportGoods.setCreateTime(new Date());
            orderServiceTransportGoodsList.add(orderServiceTransportGoods);
        }
        //配送服务
        orderServiceTransportVO.setOrderServiceTransportGoodsList(orderServiceTransportGoodsList);
        //获取配送服务详情
        QueryWrapper<ServiceShelf> serviceShelfTransportQueryWrapper=new QueryWrapper<>();
        serviceShelfTransportQueryWrapper.eq("SS_SERVICE_CLASS_DBID",serviceClass);
        ServiceShelf serviceShelfTransport=serviceShelfMapper.selectOne(serviceShelfTransportQueryWrapper);
        orderServiceTransportVO.setPhone(serviceShelfTransport.getSsPhone());
        orderServiceTransportVO.setPerson(serviceShelfTransport.getSsPerson());
        return orderServiceTransportVO;
    }

    /**
     * 生成质控服务订单
     *
     * @param orderInfoVO
     * @param orderId
     * @param userPhone
     * @param flagMap
     * @return
     */
    private List<OrderServiceQualityVO> addOrderServiceQuality(OrderInfoVO orderInfoVO, String orderId, String userPhone, Map<String, Integer> flagMap) {
        List<OrderServiceQualityVO> orderServiceQualityVOList = orderInfoVO.getOrderServiceQualityVOList();
        for (OrderServiceQualityVO orderServiceQualityVO : orderServiceQualityVOList) {
//            String osqId = NumberFormatUtil.numberFormat(6, orderInfoMapper.getOrderQualityNo());
//            orderServiceQualityVO.setOsqId(osqId);
            orderServiceQualityVO.setOsqState("0");
            PurchaseToProjectRedisMO purchaseToProjectRedisMO = projectService.getPurchaseToProjectFromRedis(orderInfoVO.getPlanPurchaseId());
            if (purchaseToProjectRedisMO != null) {
                orderServiceQualityVO.setOsqName(purchaseToProjectRedisMO.getpCompany() + "-" + purchaseToProjectRedisMO.getpName() + "-质控服务订单");
            }
            String shopName = orderInfoMapper.selectShopName(orderServiceQualityVO.getOsqShopId());
            orderServiceQualityVO.setOsqServiceUnit(shopName);
            orderServiceQualityVO.setOrderId(orderId);
            orderServiceQualityVO.setCreateUserId(UserSession.getUserId());
            orderServiceQualityVO.setCreateUser(UserSession.getUserName());
            orderServiceQualityVO.setCreateTime(new Date());
            orderServiceQualityVO.setCreateUserPhone(userPhone);
            Map<Object, Object> shopMap = redisUtil.hmget("shopInfoMap");
            if (!redisUtil.hasKey("shopInfoMap") || shopMap.size() == 0 || redisUtil.hmget("shopInfoMap").get(orderServiceQualityVO.getOsqShopId()) == null) {
                userCompanyInfoService.putShopInfoToRedis();
            }
            String serviceAddress = orderServiceQualityVO.getOsqServiceAddress();
            ShopInfoToCompRedisMO shopInfoToComp = (ShopInfoToCompRedisMO) redisUtil.hmget("shopInfoMap").get(orderServiceQualityVO.getOsqShopId());
            if (shopInfoToComp != null) {
                orderServiceQualityVO.setOsqServiceUnit(shopInfoToComp.getCsShopName());
                orderServiceQualityVO.setOsqContactsMan(shopInfoToComp.getUciRepresentative());
                orderServiceQualityVO.setOsqContactsManPhone(shopInfoToComp.getUciTelphone());
                orderServiceQualityVO.setOsqServiceAddress(shopInfoToComp.getUciBusinessAddress());
            }
            List<OrderGoods> orderGoodsList = orderInfoVO.getOrderGoodsList();
            //获取商品物料编码
            List<String> goodsDbIdList = getGoodsDbIdList(orderGoodsList);
            //传过来的服务分类
            String serviceClass = orderServiceQualityVO.getOsqQualityType();
            //查询商品服务
            List<MatServiceClassMO> matServiceClassMOList = orderGoodsMapper.selectGoodsServiceClass(
                    goodsDbIdList,
                    serviceClass,
                    flagMap.get(serviceClass),
                    orderServiceQualityVO.getOsqShopId());
            Map<String, MatServiceClassMO> matServiceClassMOMap = new HashMap<>(orderGoodsList.size());
            if (matServiceClassMOList.size() > 0) {
                for (MatServiceClassMO matServiceClassMO : matServiceClassMOList) {
                    matServiceClassMOMap.put(matServiceClassMO.getGoodsDbid(), matServiceClassMO);
                }
            }
            List<OrderServiceQualityGoods> orderServiceQualityGoodsList = new ArrayList<>(orderInfoVO.getOrderGoodsList().size());
            ShopInfoToCompRedisMO shopInfoToCompRedisMO = userCompanyInfoService.getShopInfoToCompFromRedis(orderInfoVO.getOrderShopId());
            //结算点
            String settlePoint;
            if (orderInfoVO.getOrderServiceSettleVO() != null) {
                settlePoint = orderInfoVO.getOrderServiceSettleVO().getOsseType() == "fwfl014" ? "非代储（入库）结算" : "代储（出库）结算";
            } else {
                //如果没有选择，则默认
                settlePoint = "非代储（入库）结算";
            }
            for (OrderGoods orderGoods : orderInfoVO.getOrderGoodsList()) {
                OrderServiceQualityGoods orderServiceQualityGoods = new OrderServiceQualityGoods();
//                orderServiceQualityGoods.setOsqId(osqId);
                orderServiceQualityGoods.setOsqgId(IdGenerator.UUID());
                orderServiceQualityGoods.setOsqgOrderId(orderId);
                orderServiceQualityGoods.setOsqgGoodsDbid(orderGoods.getGoodsDbid());
                orderServiceQualityGoods.setOsqgGoodsName(orderGoods.getGoodsName());
                orderServiceQualityGoods.setOsqgGoodsNumber(orderGoods.getOgGoodsNumber());
                orderServiceQualityGoods.setOsqgPrice(orderGoods.getOgGoodsPrice());
                orderServiceQualityGoods.setOsqgGoodsUnit(orderGoods.getOgGoodsUnit());
                orderServiceQualityGoods.setOsqgManNumber(orderServiceQualityVO.getOsqgManNumber());
                orderServiceQualityGoods.setOsqgDayNumber(orderServiceQualityVO.getOsqgDayNumber());
                orderServiceQualityGoods.setOsqgQualityAddress(serviceAddress);
                if (shopInfoToCompRedisMO != null) {
                    orderServiceQualityGoods.setOsqgUciName(shopInfoToCompRedisMO.getCsShopName());
                }
                orderServiceQualityGoods.setOsqgSettlePoint(settlePoint);
                if (matServiceClassMOMap.size() > 0 && matServiceClassMOMap.get(orderGoods.getGoodsDbid()) != null) {
                    orderServiceQualityGoods.setOsqgValuationUnit(matServiceClassMOMap.get(orderGoods.getGoodsDbid()).getSpPriceUnit());
                    orderServiceQualityGoods.setOsqgPrice(matServiceClassMOMap.get(orderGoods.getGoodsDbid()).getSpServiceCharge());
                    orderServiceQualityGoods.setOsqgGoodsClass(matServiceClassMOMap.get(orderGoods.getGoodsDbid()).getGoodsClass());
                    orderServiceQualityGoods.setOsqgGoodsSingleWeight(matServiceClassMOMap.get(orderGoods.getGoodsDbid()).getGoodsGoodsWeight().floatValue());
                }
                orderServiceQualityGoodsList.add(orderServiceQualityGoods);
            }
            orderServiceQualityVO.setOrderServiceQualityGoodsList(orderServiceQualityGoodsList);
            //获取质控服务详情
            QueryWrapper<ServiceShelf> serviceShelfQulityQueryWrapper=new QueryWrapper<>();
            serviceShelfQulityQueryWrapper.eq("SS_SERVICE_CLASS_DBID",serviceClass);
            ServiceShelf serviceShelfQulity=serviceShelfMapper.selectOne(serviceShelfQulityQueryWrapper);
            orderServiceQualityVO.setPerson(serviceShelfQulity.getSsPerson());
            orderServiceQualityVO.setPhone(serviceShelfQulity.getSsPhone());
        }
        return orderServiceQualityVOList;
    }

    /**
     * 生成仓储服务订单
     *
     * @param orderInfoVO
     * @param orderId
     * @param userPhone
     * @param flagMap
     * @return
     */
    private List<OrderServiceStorageVO> addOrderServiceStorage(OrderInfoVO orderInfoVO, String orderId, String userPhone, Map<String, Integer> flagMap) {
        List<OrderServiceStorageVO> orderServiceStorageVOList = orderInfoVO.getOrderServiceStorageVOList();
        List<GoodsInfo> goodsInfoList = getGoodsInfoListByDbId(orderInfoVO.getOrderGoodsList());
        Map<String, GoodsInfo> goodsInfoMap = new HashMap<>(goodsInfoList.size());
        for (GoodsInfo goodsInfo : goodsInfoList) {
            goodsInfoMap.put(goodsInfo.getGoodsDbid(), goodsInfo);
        }
        for (OrderServiceStorageVO orderServiceStorageVO : orderServiceStorageVOList) {
//            String ossId = NumberFormatUtil.numberFormat(6, orderInfoMapper.getOrderStorageNo());
//            orderServiceStorageVO.setOssId(ossId);
            orderServiceStorageVO.setOssState("0");
            PurchaseToProjectRedisMO purchaseToProjectRedisMO = projectService.getPurchaseToProjectFromRedis(orderInfoVO.getPlanPurchaseId());
            if (purchaseToProjectRedisMO != null) {
                orderServiceStorageVO.setOssName(purchaseToProjectRedisMO.getpCompany() + "-" + purchaseToProjectRedisMO.getpName() + "-仓储服务订单");
            }
            Map<Object, Object> shopMap = redisUtil.hmget("shopInfoMap");
            if (!redisUtil.hasKey("shopInfoMap") || shopMap.size() == 0 || redisUtil.hmget("shopInfoMap").get(orderServiceStorageVO.getOssShopId()) == null) {
                userCompanyInfoService.putShopInfoToRedis();
            }
            String storageAddress = orderServiceStorageVO.getOssServiceAddress();
            ShopInfoToCompRedisMO shopInfoToComp = (ShopInfoToCompRedisMO) redisUtil.hmget("shopInfoMap").get(orderServiceStorageVO.getOssShopId());
            if (shopInfoToComp != null) {
                orderServiceStorageVO.setOssServiceUnit(shopInfoToComp.getCsShopName());
                orderServiceStorageVO.setOssContactsMan(shopInfoToComp.getUciRepresentative());
                orderServiceStorageVO.setOssContactsManPhone(shopInfoToComp.getUciTelphone());
                orderServiceStorageVO.setOssServiceAddress(shopInfoToComp.getUciBusinessAddress());
            }
//            String shopName = orderInfoMapper.selectShopName(orderServiceStorageVO.getOssShopId());
//            orderServiceStorageVO.setOssServiceUnit(shopName);
            orderServiceStorageVO.setOrderId(orderId);
            orderServiceStorageVO.setCreateUserId(UserSession.getUserId());
            orderServiceStorageVO.setCreateUser(UserSession.getUserName());
            orderServiceStorageVO.setCreateTime(new Date());
            orderServiceStorageVO.setCreateUserPhone(userPhone);
            List<OrderGoods> orderGoodsList = orderInfoVO.getOrderGoodsList();
            List<String> goodsDbIdList = getGoodsDbIdList(orderGoodsList);
            //传过来的服务分类
            String serviceClass = orderServiceStorageVO.getOssStorageType();
            //查询商品服务
            List<MatServiceClassMO> matServiceClassMOList = orderGoodsMapper.selectGoodsServiceClass(
                    goodsDbIdList,
                    serviceClass,
                    flagMap.get(serviceClass),
                    orderServiceStorageVO.getOssShopId());
            Map<String, MatServiceClassMO> matServiceClassMOMap = new HashMap<>(orderGoodsList.size());
            if (matServiceClassMOList.size() > 0) {
                for (MatServiceClassMO matServiceClassMO : matServiceClassMOList) {
                    matServiceClassMOMap.put(matServiceClassMO.getGoodsDbid(), matServiceClassMO);
                }
            }
            ShopInfoToCompRedisMO shopInfoToCompRedisMO = userCompanyInfoService.getShopInfoToCompFromRedis(orderInfoVO.getOrderShopId());
            //结算点
            String settlePoint;
            if (orderInfoVO.getOrderServiceSettleVO() != null) {
                settlePoint = orderInfoVO.getOrderServiceSettleVO().getOsseType() == "fwfl014" ? "非代储（入库）结算" : "代储（出库）结算";
            } else {
                //如果没有选择，则默认
                settlePoint = "非代储（入库）结算";
            }
            List<OrderServiceStorageGoods> orderServiceStorageGoodsList = new ArrayList<>(orderInfoVO.getOrderGoodsList().size());
            for (OrderGoods orderGoods : orderInfoVO.getOrderGoodsList()) {
                OrderServiceStorageGoods orderServiceStorageGoods = new OrderServiceStorageGoods();
                orderServiceStorageGoods.setOssgId(IdGenerator.UUID());
//                orderServiceStorageGoods.setOssId(ossId);
                orderServiceStorageGoods.setOssgOrderId(orderId);
                orderServiceStorageGoods.setOssgGoodsDbid(orderGoods.getGoodsDbid());
                orderServiceStorageGoods.setOssgGoodsName(orderGoods.getGoodsName());
                orderServiceStorageGoods.setOssgGoodsNumber(orderGoods.getOgGoodsNumber());
                orderServiceStorageGoods.setOssgGoodsPrice(orderGoods.getOgGoodsPrice());
                orderServiceStorageGoods.setOssgGoodsMoney(BigDecimal.valueOf(orderGoods.getOgGoodsNumber()).multiply(orderGoods.getOgGoodsPrice()));
                orderServiceStorageGoods.setOssgGoodsUnit(orderGoods.getOgGoodsUnit());
                orderServiceStorageGoods.setOssgUciName(shopInfoToCompRedisMO.getCsShopName());
                orderServiceStorageGoods.setOssgSettlePoint(settlePoint);
                orderServiceStorageGoods.setOssgStorageData(orderServiceStorageVO.getOssServiceDays());
                orderServiceStorageGoods.setOssgStorageAddress(storageAddress);
                if (matServiceClassMOMap.size() > 0 && matServiceClassMOMap.get(orderGoods.getGoodsDbid()) != null) {
                    orderServiceStorageGoods.setOssgValuationUnit(matServiceClassMOMap.get(orderGoods.getGoodsDbid()).getSpPriceUnit());
                    orderServiceStorageGoods.setOssgPrice(matServiceClassMOMap.get(orderGoods.getGoodsDbid()).getSpServiceCharge());
                    orderServiceStorageGoods.setOssgGoodsClass(matServiceClassMOMap.get(orderGoods.getGoodsDbid()).getGoodsClass());
                    orderServiceStorageGoods.setOssgGoodsSingleWeight(matServiceClassMOMap.get(orderGoods.getGoodsDbid()).getGoodsGoodsWeight().doubleValue());
                }
                if (goodsInfoMap.get(orderGoods.getGoodsDbid()).getGoodsGoodsWeight() != null) {
                    orderServiceStorageGoods.setOssgGoodsSingleWeight(goodsInfoMap.get(orderGoods.getGoodsDbid()).getGoodsGoodsWeight().doubleValue());
                }
                orderServiceStorageGoodsList.add(orderServiceStorageGoods);
            }
            orderServiceStorageVO.setOrderServiceStorageGoodsList(orderServiceStorageGoodsList);
            //获取仓储服务详情
            QueryWrapper<ServiceShelf> serviceShelfStorageQueryWrapper=new QueryWrapper<>();
            serviceShelfStorageQueryWrapper.eq("SS_SERVICE_CLASS_DBID",serviceClass);
            ServiceShelf serviceShelfStorage=serviceShelfMapper.selectOne(serviceShelfStorageQueryWrapper);
            orderServiceStorageVO.setPhone(serviceShelfStorage.getSsPhone());
            orderServiceStorageVO.setPerson(serviceShelfStorage.getSsPerson());
        }
        return orderServiceStorageVOList;
    }

    /**
     * 生成结算服务订单
     *
     * @param orderInfoVO 前端传入的
     * @param orderId     商品订单ID
     * @param userPhone   下单人联系电话
     * @return
     */
    private OrderServiceSettleVO addOrderServiceSettle(OrderInfoVO orderInfoVO, String orderId, String userPhone, PurchaseToProjectRedisMO purchaseToProjectRedisMO) {
        //结算服务订单
        OrderServiceSettleVO orderServiceSettleVO = orderInfoVO.getOrderServiceSettleVO();
//        String ospId = NumberFormatUtil.numberFormat(6, orderInfoMapper.getOrderSettleNo());
//        orderServiceSettleVO.setOsseId(ospId);
        orderServiceSettleVO.setOrderId(orderId);
        orderServiceSettleVO.setOsseState("0");
        orderServiceSettleVO.setOssePurchaseDepartment(UserSession.getOrgId());
        if (purchaseToProjectRedisMO != null) {
            orderServiceSettleVO.setOsseProjectId(purchaseToProjectRedisMO.getpId());
            orderServiceSettleVO.setOsseProjectName(purchaseToProjectRedisMO.getpName());
            orderServiceSettleVO.setOsseOrderName(purchaseToProjectRedisMO.getpCompany() + "-" + purchaseToProjectRedisMO.getpName() + "-结算服务订单");
        }
        Map<Object, Object> shopMap = redisUtil.hmget("shopInfoMap");
        if (!redisUtil.hasKey("shopInfoMap") || shopMap.size() == 0 || redisUtil.hmget("shopInfoMap").get(orderServiceSettleVO.getOsseShopId()) == null) {
            userCompanyInfoService.putShopInfoToRedis();
        }
        ShopInfoToCompRedisMO shopInfoToComp = (ShopInfoToCompRedisMO) redisUtil.hmget("shopInfoMap").get(orderServiceSettleVO.getOsseShopId());
        if (shopInfoToComp != null) {
            orderServiceSettleVO.setOsseSupplierName(shopInfoToComp.getCsShopName());
            orderServiceSettleVO.setOsseContactMan(shopInfoToComp.getUciRepresentative());
            orderServiceSettleVO.setOsseContactPhone(shopInfoToComp.getUciTelphone());
            orderServiceSettleVO.setOsseDeliveryAddress(shopInfoToComp.getUciBusinessAddress());
        }
        orderServiceSettleVO.setCreateUserId(UserSession.getUserId());
        orderServiceSettleVO.setCreateUser(UserSession.getUserName());
        orderServiceSettleVO.setCreateUserPhone(userPhone);
        orderServiceSettleVO.setCreateTime(new Date());
        //服务价格：出库结算按普通商业银行一年贷款利率4.35% ，入库结算
        BigDecimal servicePrice;
        if ("fwfl014".equals(orderServiceSettleVO.getOsseType())) {
            servicePrice = BigDecimal.valueOf(0.0435);
        } else {
            servicePrice = BigDecimal.valueOf(0);
        }
        //采购计划中实物商品list
        List<OrderServiceSettleGoods> orderServiceSettleGoodsList = new ArrayList<>();
        //订单中实物商品list
        List<OrderGoods> orderGoodsList = orderInfoVO.getOrderGoodsList();
        for (OrderGoods orderGoods : orderGoodsList) {
            //将商品信息同步到采购服务订单下的商品表中
            OrderServiceSettleGoods orderServiceSettleGoods = new OrderServiceSettleGoods();
            orderServiceSettleGoods.setOssegId(IdGenerator.UUID());
//            orderServiceSettleGoods.setOsseId(ospId);
            orderServiceSettleGoods.setOssegGoodsDbid(orderGoods.getGoodsDbid());
            orderServiceSettleGoods.setOssegGoodsName(orderGoods.getGoodsName());
            orderServiceSettleGoods.setOssegGoodsNumber(orderGoods.getOgGoodsNumber());
            orderServiceSettleGoods.setOssegGoodsUnit(orderGoods.getOgGoodsUnit());
            orderServiceSettleGoods.setOssegPrice(orderGoods.getOgGoodsPrice());
            //商品采购金额
            BigDecimal goodsMoney = orderGoods.getOgGoodsPrice().multiply(BigDecimal.valueOf(orderGoods.getOgGoodsNumber()));
            orderServiceSettleGoods.setOssegMoney(goodsMoney.multiply(servicePrice));
            orderServiceSettleGoods.setOssegStorageDays("30");
            orderServiceSettleGoods.setCreateUser(UserSession.getUserId());
            orderServiceSettleGoods.setCreateTime(new Date());
            orderServiceSettleGoodsList.add(orderServiceSettleGoods);
        }
        orderServiceSettleVO.setOrderServiceSettleGoodsList(orderServiceSettleGoodsList);
        //获取结算服务详情
        QueryWrapper<ServiceShelf> serviceShelfSettleQueryWrapper=new QueryWrapper<>();
        serviceShelfSettleQueryWrapper.eq("SS_SERVICE_CLASS_DBID",orderServiceSettleVO.getOsseType());
        ServiceShelf serviceShelfSettle=serviceShelfMapper.selectOne(serviceShelfSettleQueryWrapper);
        orderServiceSettleVO.setPerson(serviceShelfSettle.getSsPerson());
        orderServiceSettleVO.setPhone(serviceShelfSettle.getSsPhone());
        return orderServiceSettleVO;
    }


    /**
     * 获取用户订单
     *
     * @param orderInfo
     */
    @Override
    @DoPage
    public List<OrderInfo> getOrder(OrderInfo orderInfo) {
        QueryWrapper<OrderInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("CREATE_USER_ID", UserSession.getUserId())
                .like(orderInfo.getOrderProjectName() != null, "ORDER_PROJECT_NAME", orderInfo.getOrderProjectName())
                .like(orderInfo.getOrderSupplierName() != null, "ORDER_SUPPLIER_NAME", orderInfo.getOrderSupplierName())
                .eq(orderInfo.getOrderState() != null, "ORDER_STATE", orderInfo.getOrderState());
        List<OrderInfo> orderInfoList = orderInfoMapper.selectList(queryWrapper);
        if (orderInfoList != null && !orderInfoList.isEmpty()) {
            orderInfoList.forEach(orderInfoNew -> {
                CiccRecord ciccRecord = CiccRecordUtil.getCiccRecord(CiccTableNameEnum.ORDER_CONFIRM_STATUS.getCodeValue(), String.valueOf(orderInfoNew.getOrderState()));
                orderInfoNew.setOrderStateLabel(ciccRecord.getLabel());
            });
        }
        return orderInfoList;
    }

    /**
     * 根据订单获取订单详细信息
     * 包含订单下的所有服务订单和服务下的所有商品
     *
     * @param orderId
     * @return
     */
    @Override
    public OrderInfoVO getOrderDetail(String orderId) {
        OrderInfo orderInfo = orderInfoMapper.selectById(orderId);
        OrderInfoVO orderInfoVO = new OrderInfoVO();
        BeanUtils.copyProperties(orderInfo, orderInfoVO);
        QueryWrapper<OrderGoods> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ORDER_ID", orderId);
        List<OrderGoods> orderGoodsList = orderGoodsMapper.selectList(queryWrapper);
        //将物料编码换成11位的
        String matCode=null;
        orderGoodsList.forEach(n-> n.setGoodsDbid(orderInfoMapper.getMatCodeByGoodsId(n.getGoodsDbid())));
        orderInfoVO.setOrderGoodsList(orderGoodsList);
        //查询采购服务订单及订单下的商品
        QueryWrapper<OrderServicePurchase> purchaseQueryWrapper = new QueryWrapper<>();
        purchaseQueryWrapper.eq("ORDER_ID", orderId);
        OrderServicePurchase orderServicePurchase = orderServicePurchaseMapper.selectOne(purchaseQueryWrapper);
        //获取采购服务的服务详情
        String purchaseType=orderServicePurchase.getOspPurchaseType();
        QueryWrapper<ServiceShelf> serviceShelfQueryWrapper=new QueryWrapper<>();
        serviceShelfQueryWrapper.eq("SS_SERVICE_CLASS_NAME",purchaseType);
        ServiceShelf serviceShelf=serviceShelfMapper.selectOne(serviceShelfQueryWrapper);

        if (orderServicePurchase != null) {
            OrderServicePurchaseVO orderServicePurchaseVO = new OrderServicePurchaseVO();
            orderServicePurchaseVO.setPerson(serviceShelf.getSsPerson());
            orderServicePurchaseVO.setPhone(serviceShelf.getSsPhone());
            BeanUtils.copyProperties(orderServicePurchase, orderServicePurchaseVO);
            QueryWrapper<OrderServicePurchaseGoods> purchaseGoodsQueryWrapper = new QueryWrapper<>();
            purchaseGoodsQueryWrapper.eq("OSP_ID", orderServicePurchaseVO.getOspId());
            List<OrderServicePurchaseGoods> purchaseGoodsList = orderServicePurchaseGoodsMapper.selectList(purchaseGoodsQueryWrapper);
            purchaseGoodsList.forEach(n-> n.setOspgGoodsDbid(orderInfoMapper.getMatCodeByGoodsId(n.getOspgGoodsDbid())));
            orderServicePurchaseVO.setOrderServicePurchaseGoodsList(purchaseGoodsList);
            orderInfoVO.setOrderServicePurchaseVO(orderServicePurchaseVO);
        }
        //查询配送服务订单及订单下的商品
        QueryWrapper<OrderServiceTransport> transportQueryWrapper = new QueryWrapper<>();
        transportQueryWrapper.eq("ORDER_ID", orderId);
        OrderServiceTransport orderServiceTransport = orderServiceTransportMapper.selectOne(transportQueryWrapper);
        //获取配送服务的服务详情
        String transportType=orderServiceTransport.getOstTransportType();
        QueryWrapper<ServiceShelf> serviceShelfTransportQueryWrapper=new QueryWrapper<>();
        serviceShelfTransportQueryWrapper.eq("SS_SERVICE_CLASS_DBID",transportType);
        ServiceShelf serviceShelfTransport=serviceShelfMapper.selectOne(serviceShelfTransportQueryWrapper);

        if (orderServiceTransport != null) {
            OrderServiceTransportVO orderServiceTransportVO = new OrderServiceTransportVO();
            orderServiceTransportVO.setPerson(serviceShelfTransport.getSsPerson());
            orderServiceTransportVO.setPhone(serviceShelfTransport.getSsPhone());
            BeanUtils.copyProperties(orderServiceTransport, orderServiceTransportVO);
            QueryWrapper<OrderServiceTransportGoods> transportGoodsQueryWrapper = new QueryWrapper<>();
            transportGoodsQueryWrapper.eq("OST_ID", orderServiceTransportVO.getOstId());
            List<OrderServiceTransportGoods> transportGoodsList = orderServiceTransportGoodsMapper.selectList(transportGoodsQueryWrapper);
            transportGoodsList.forEach(n-> n.setOstgGoodsDbid(orderInfoMapper.getMatCodeByGoodsId(n.getOstgGoodsDbid())));
            orderServiceTransportVO.setOrderServiceTransportGoodsList(transportGoodsList);
            orderInfoVO.setOrderServiceTransportVO(orderServiceTransportVO);
        }

        //查询仓储服务订单及订单下的商品
        QueryWrapper<OrderServiceStorage> storageQueryWrapper = new QueryWrapper<>();
        storageQueryWrapper.eq("ORDER_ID", orderId);
        List<OrderServiceStorage> orderServiceStorageList = orderServiceStorageMapper.selectList(storageQueryWrapper);
        if (orderServiceStorageList.size() > 0) {
            List<OrderServiceStorageVO> orderServiceStorageVOList = new ArrayList<>(2);
            for (OrderServiceStorage orderServiceStorage : orderServiceStorageList) {
                //获取仓储服务订单的服务详情
                String storageType=orderServiceStorage.getOssStorageType();
                QueryWrapper<ServiceShelf> serviceShelfStorageQueryWrapper=new QueryWrapper<>();
                serviceShelfStorageQueryWrapper.eq("SS_SERVICE_CLASS_DBID",storageType);
                ServiceShelf serviceShelfStorage=serviceShelfMapper.selectOne(serviceShelfStorageQueryWrapper);

                OrderServiceStorageVO orderServiceStorageVO = new OrderServiceStorageVO();
                orderServiceStorageVO.setPerson(serviceShelfStorage.getSsPerson());
                orderServiceStorageVO.setPhone(serviceShelfStorage.getSsPhone());
                QueryWrapper<OrderServiceStorageGoods> storageGoodsQueryWrapper = new QueryWrapper<>();
                storageGoodsQueryWrapper.eq("OSS_ID", orderServiceStorage.getOssId());
                List<OrderServiceStorageGoods> storageGoodsList = orderServiceStorageGoodsMapper.selectList(storageGoodsQueryWrapper);
                BeanUtils.copyProperties(orderServiceStorage, orderServiceStorageVO);
                storageGoodsList.forEach(n-> n.setOssgGoodsDbid(orderInfoMapper.getMatCodeByGoodsId(n.getOssgGoodsDbid())));
                orderServiceStorageVO.setOrderServiceStorageGoodsList(storageGoodsList);
                orderServiceStorageVOList.add(orderServiceStorageVO);
            }
            orderInfoVO.setOrderServiceStorageVOList(orderServiceStorageVOList);
        }

        //查询质控服务订单及订单下的商品
        QueryWrapper<OrderServiceQuality> qualityQueryWrapper = new QueryWrapper<>();
        qualityQueryWrapper.eq("ORDER_ID", orderId);
        List<OrderServiceQuality> orderServiceQualityList = orderServiceQualityMapper.selectList(qualityQueryWrapper);
        if (orderServiceQualityList.size() > 0) {
            List<OrderServiceQualityVO> orderServiceQualityVOList = new ArrayList<>(2);
            for (OrderServiceQuality orderServiceQuality : orderServiceQualityList) {
                //获取质控服务详情
                String qulityType=orderServiceQuality.getOsqQualityType();
                QueryWrapper<ServiceShelf> serviceShelfQulityQueryWrapper=new QueryWrapper<>();
                serviceShelfQulityQueryWrapper.eq("SS_SERVICE_CLASS_DBID",qulityType);
                ServiceShelf serviceShelfQulity=serviceShelfMapper.selectOne(serviceShelfQulityQueryWrapper);

                OrderServiceQualityVO orderServiceQualityVO = new OrderServiceQualityVO();
                orderServiceQualityVO.setPerson(serviceShelfQulity.getSsPerson());
                orderServiceQualityVO.setPhone(serviceShelfQulity.getSsPhone());
                QueryWrapper<OrderServiceQualityGoods> qualityGoodsQueryWrapper = new QueryWrapper<>();
                qualityGoodsQueryWrapper.eq("OSQ_ID", orderServiceQuality.getOsqId());
                List<OrderServiceQualityGoods> qualityGoodsList = orderServiceQualityGoodsMapper.selectList(qualityGoodsQueryWrapper);
                BeanUtils.copyProperties(orderServiceQuality, orderServiceQualityVO);
                qualityGoodsList.forEach(n-> n.setOsqgGoodsDbid(orderInfoMapper.getMatCodeByGoodsId(n.getOsqgGoodsDbid())));
                orderServiceQualityVO.setOrderServiceQualityGoodsList(qualityGoodsList);
                orderServiceQualityVOList.add(orderServiceQualityVO);
            }
            orderInfoVO.setOrderServiceQualityVOList(orderServiceQualityVOList);
        }

        //查询结算服务订单及订单下的商品
        QueryWrapper<OrderServiceSettle> settleQueryWrapper = new QueryWrapper<>();
        settleQueryWrapper.eq("ORDER_ID", orderId);
        OrderServiceSettle orderServiceSettle = orderServiceSettleMapper.selectOne(settleQueryWrapper);
        if (orderServiceSettle != null) {
            //获取结算服务详情
            String settleType=orderServiceSettle.getOsseType();
            QueryWrapper<ServiceShelf> serviceShelfSettleQueryWrapper=new QueryWrapper<>();
            serviceShelfSettleQueryWrapper.eq("SS_SERVICE_CLASS_DBID",settleType);
            ServiceShelf serviceShelfSettle=serviceShelfMapper.selectOne(serviceShelfSettleQueryWrapper);
            OrderServiceSettleVO orderServiceSettleVO = new OrderServiceSettleVO();
            orderServiceSettleVO.setPerson(serviceShelfSettle.getSsPerson());
            orderServiceSettleVO.setPhone(serviceShelfSettle.getSsPhone());
            BeanUtils.copyProperties(orderServiceSettle, orderServiceSettleVO);
            QueryWrapper<OrderServiceSettleGoods> settleGoodsQueryWrapper = new QueryWrapper<>();
            settleGoodsQueryWrapper.eq("OSSE_ID", orderServiceSettleVO.getOsseId());
            List<OrderServiceSettleGoods> serviceSettleGoodsList = orderServiceSettleGoodsMapper.selectList(settleGoodsQueryWrapper);
            serviceSettleGoodsList.forEach(n-> n.setOssegGoodsDbid(orderInfoMapper.getMatCodeByGoodsId(n.getOssegGoodsDbid())));
            orderServiceSettleVO.setOrderServiceSettleGoodsList(serviceSettleGoodsList);
            orderInfoVO.setOrderServiceSettleVO(orderServiceSettleVO);
        }
        //返回订单详情
        return orderInfoVO;
    }

    /**
     * @param orderId
     * @param orderState
     */
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    @Override
    public void updateOrderState(String orderId, String orderState) {
        orderInfoMapper.updateOrderState(orderId, orderState);
        String state;
        if ("2".equals(orderState)) {
            state = "1";
            //orderInfoMapper.updatePurchaseOrderState(orderId, state);
            orderInfoMapper.updateTransportOrderState(orderId, state);
            orderInfoMapper.updateQualityOrderState(orderId, state);
            orderInfoMapper.updateStorageOrderState(orderId, state);
            orderInfoMapper.updateSettleOrderState(orderId, state);
        }
        if ("2".equals(orderState)) {
            QueryWrapper<OrderServicePurchase> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("ORDER_ID", orderId);
            OrderServicePurchase orderServicePurchase = orderServicePurchaseMapper.selectOne(queryWrapper);
            orderServicePurchase.setOspState(SERVICE_ORDER_AGREED_STATE);
            orderServicePurchase.setUpdateTime(new Date());
            orderServicePurchase.setUpdateUser(UserSession.getUserId());
            orderServicePurchaseMapper.updateById(orderServicePurchase);
        }

    }

    @Override
    public List<Map<String, Object>> getTeVideo() {
        List<Map<String, Object>> videoList = orderInfoMapper.getTeVideo();
        List<Map<String, Object>> list = new ArrayList<>();
        Map<String, Object> map1 = new HashMap();
        for (Map map : videoList) {
            StringBuffer parts = new StringBuffer("");
            parts.append(map.get("videoAddress") + "|");
            parts.append(map.get("videoName"));
            map.get("tName").toString();
            map1.put(map.get("tName").toString(), parts);
        }
        map1.put("serNo", videoList.get(0).get("serNo"));
        list.add(map1);
        return list;
    }


    @Override
    public List<Map<String, Object>> getProProcessInfo(ProProcessParam proProcessParam) throws ParseException {
        String startDate = null;
        String endDate = null;
        String nowDate = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        if (DateLogoEnum.WEEK.getKey().equals(proProcessParam.getDateIdent())) {
            String startEndDate = DateUtils.getFirstAndLastOfWeek(nowDate, "yyyy-MM-dd", "yyyy-MM-dd");
            if (StringUtils.isNotEmpty(startEndDate)) {
                String[] strings = startEndDate.split("_");
                startDate = strings[0];
                endDate = strings[1];
            }
        } else if (DateLogoEnum.MONTH.getKey().equals(proProcessParam.getDateIdent())) {
            String startEndDate = DateUtils.getFirstAndLastOfMonth(nowDate, "yyyy-MM-dd", "yyyy-MM-dd");
            if (StringUtils.isNotEmpty(startEndDate)) {
                String[] strings = startEndDate.split("_");
                startDate = strings[0];
                endDate = strings[1];
            }
        } else if (DateLogoEnum.QUARTER.getKey().equals(proProcessParam.getDateIdent())) {
            String startEndDate = DateUtils.getFirstAndLastOfQuarter(nowDate, "yyyy-MM-dd", "yyyy-MM-dd");
            if (StringUtils.isNotEmpty(startEndDate)) {
                String[] strings = startEndDate.split("_");
                startDate = strings[0];
                endDate = strings[1];
            }
        }

        Date date = new Date();
        if (StringUtils.isNotEmpty(proProcessParam.getStartTime())) {
            date = new SimpleDateFormat("yyyy-MM-dd").parse(proProcessParam.getStartTime());
        } else if (StringUtils.isNotEmpty(proProcessParam.getDateIdent())) {
            date = new SimpleDateFormat("yyyy-MM-dd").parse(startDate);
        } else {
            date = null;
        }
        Date date1 = new Date();
        if (StringUtils.isNotEmpty(proProcessParam.getEndTime())) {
            date1 = new SimpleDateFormat("yyyy-MM-dd").parse(proProcessParam.getEndTime());
        } else if (StringUtils.isNotEmpty(proProcessParam.getDateIdent())) {
            date1 = new SimpleDateFormat("yyyy-MM-dd").parse(endDate);
        } else {
            date1 = null;
        }
        proProcessParam.setStartTimeDate(date);
        proProcessParam.setEndTimeDate(date1);
        return orderInfoMapper.getProProcessInfo(proProcessParam);
    }

    @Override
    public List<Map<String, Object>> getVideoInfo(String saleOrderNo, String matId) {

        return orderInfoMapper.getVideoInfo(saleOrderNo);
    }

    @Override
    public List<Map<String, Object>> getAllTechnologyName(String saleOrderNo, String matId) {
        List<Map<String, Object>> list = new ArrayList<>();
        List<Map<String, Object>> videoMap = getVideoInfo(saleOrderNo, matId);
        if (videoMap != null && videoMap.size() > 0) {
            Map<String, Object> serMap = new LinkedHashMap<String, Object>();
            serMap.put("serialNo", videoMap.get(0).get("serialNo"));
            list.add(serMap);
            String key = "key";
            int n = 1;
            for (Map map : videoMap) {
                Map<String, Object> nameMap = new LinkedHashMap<String, Object>();
                nameMap.put(map.get("tId").toString(), map.get("technologyName"));
                list.add(nameMap);
                n++;
            }
            return list;
        }
        return list;
    }

    @Override
    public List<Map<String, Object>> getVideoInfoList(String saleOrderNo, String matId) {
        List<Map<String, Object>> videoList = getVideoInfo(saleOrderNo, matId);
        List<Map<String, Object>> mapList = Lists.newArrayList();
        if (videoList != null && videoList.size() > 0) {
            Set<String> serialNos = new HashSet<>();
            for (Map<String, Object> map : videoList) {
                serialNos.add(map.get("serialNo").toString());
            }
            //新的返回结果
            for (String serialNo : serialNos) {
                Map<String, Object> map = new HashMap<>();
                map.put("serialNo", serialNo);
                for (Map<String, Object> t : videoList) {
                    if (t.get("serialNo").toString().equals(serialNo)) {
                        Map<String, Object> fileMap = new HashMap<>();
                        fileMap.put("fileId", t.get("videoAddress"));
                        fileMap.put("fileName", t.get("videoName"));
                        map.put(t.get("tId").toString(), fileMap);
                    }
                }
                mapList.add(map);
            }
            return mapList;
        }
        return mapList;
    }

    @Override
    public List<Map<String, Object>> getPurOrderDetail(String productProduceProcessId) {
        return orderInfoMapper.getOrderDetail(productProduceProcessId);
    }

    @Override
    public List<Map<String, Object>> getProductQltReportList(ProductQltReportParam productQltReportParam) throws ParseException {
        String startDate = null;
        String endDate = null;
        String nowDate = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        if (DateLogoEnum.WEEK.getKey().equals(productQltReportParam.getDateIdent())) {
            String startEndDate = DateUtils.getFirstAndLastOfWeek(nowDate, "yyyy-MM-dd", "yyyy-MM-dd");
            if (StringUtils.isNotEmpty(startEndDate)) {
                String[] strings = startEndDate.split("_");
                startDate = strings[0];
                endDate = strings[1];
            }
        } else if (DateLogoEnum.MONTH.getKey().equals(productQltReportParam.getDateIdent())) {
            String startEndDate = DateUtils.getFirstAndLastOfMonth(nowDate, "yyyy-MM-dd", "yyyy-MM-dd");
            if (StringUtils.isNotEmpty(startEndDate)) {
                String[] strings = startEndDate.split("_");
                startDate = strings[0];
                endDate = strings[1];
            }
        } else if (DateLogoEnum.QUARTER.getKey().equals(productQltReportParam.getDateIdent())) {
            String startEndDate = DateUtils.getFirstAndLastOfQuarter(nowDate, "yyyy-MM-dd", "yyyy-MM-dd");
            if (StringUtils.isNotEmpty(startEndDate)) {
                String[] strings = startEndDate.split("_");
                startDate = strings[0];
                endDate = strings[1];
            }
        } else if (DateLogoEnum.YEAR.getKey().equals(productQltReportParam.getDateIdent())) {
            String startEndDate = DateUtils.getFirstAndLastOfYear(nowDate, "yyyy-MM-dd", "yyyy-MM-dd");
            if (StringUtils.isNotEmpty(startEndDate)) {
                String[] strings = startEndDate.split("_");
                startDate = strings[0];
                endDate = strings[1];
            }
        }


        Date date = new Date();
        if (StringUtils.isNotEmpty(productQltReportParam.getDateIdent())) {
            date = new SimpleDateFormat("yyyy-MM-dd").parse(startDate);
        } else {
            date = null;
        }
        Date date1 = new Date();
        if (StringUtils.isNotEmpty(productQltReportParam.getDateIdent())) {
            date1 = new SimpleDateFormat("yyyy-MM-dd").parse(endDate);
        } else {
            date1 = null;
        }
        productQltReportParam.setStartTimeDate(date);
        productQltReportParam.setEndTimeDate(date1);
        return orderInfoMapper.getProductQltReportList(productQltReportParam);
    }

    @Override
    public List<Map<String, Object>> getMatTechnologyQltReportList(String qltId, String isVideo) {
        List<Map<String, Object>> matList1 = new ArrayList<>();
        List<Map<String, Object>> matList2 = new ArrayList<>();
        List<Map<String, Object>> list = orderInfoMapper.getMatTechnologyQltReportList(qltId, isVideo);
        for (Map map : list) {
            if (map != null && ("").equals(map.get("videoAddress"))) {
                matList1.add(map);
            } else {
                matList2.add(map);
            }
        }
        if (isVideo != null && ("0").equals(isVideo)) {
            return matList1;
        } else if (isVideo != null && ("1").equals(isVideo)) {
            return matList2;
        }
        return orderInfoMapper.getMatTechnologyQltReportList(qltId, isVideo);
    }

    @Override
    public List<Map<String, Object>> getTechnologyReportList(TechnologyReportParam technologyReportParam) {
        return orderInfoMapper.getTechnologyReportList(technologyReportParam);
    }

    @Override
    public String getTechnologyFile(String mqId) {
        List<Map<String, Object>> list = orderInfoMapper.getFileList(mqId);
        StringBuffer parts = new StringBuffer("");
        if (list == null || list.size() < 1) {
            return parts.toString();
        }
        if (list != null && list.size() > 1) {
            list.stream().forEach(t -> {
                parts.append(t.get("fileAddress") + "<");
            });
            parts.delete(parts.length() - 1, parts.length());
            parts.append("|");
            list.stream().forEach(t -> {
                parts.append(t.get("fileName") + "<");
            });
            parts.delete(parts.length() - 1, parts.length());
        } else {
            parts.append(list.get(0).get("fileAddress")).append("|").append(list.get(0).get("fileName"));
        }
        return parts.toString();
    }

    @Override
    public List<Map<String, Object>> getStockReportList(StockReportParam stockReportParam) {
        return orderInfoMapper.getStockReportList(stockReportParam);
    }

    @Override
    public List<ExcelOrderInfo> getExcelOrderInfoList(ProProcessParam processInfoParam) throws ParseException {
        List<ExcelOrderInfo> list = new ArrayList<>();
        List<Map<String, Object>> mlist = getProProcessInfo(processInfoParam);
        for (Map map : mlist) {
            ExcelOrderInfo excelOrderInfo = new ExcelOrderInfo();
            excelOrderInfo.setPurchase((String) map.get("purchase"));
            excelOrderInfo.setSupName((String) map.get("supName"));
            excelOrderInfo.setSaleOrderNo((String) map.get("saleOrderNo"));
            excelOrderInfo.setMatName((String) map.get("matName"));
            excelOrderInfo.setMatCode((String) map.get("matCode"));
            excelOrderInfo.setMatDescription((String) map.get("matDescription"));
            excelOrderInfo.setUnitLab((String) map.get("unitLab"));
            excelOrderInfo.setDeliveryQty(map.get("deliveryQty").toString());
            if (map.get("deliveryDate") != null) {
                excelOrderInfo.setDeliveryDate(map.get("deliveryDate").toString());
            }
            excelOrderInfo.setCompleteQty(map.get("completeQty").toString());
            if (map.get("produceProcess") != null) {
                excelOrderInfo.setProduceProcess((String) map.get("produceProcess"));
            }
            list.add(excelOrderInfo);
        }
        return list;
    }

    @Override
    public void exportOrderInfo(HttpServletResponse response, ProProcessParam processInfoParam) throws IOException, ParseException {
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment; filename" + "param.xlsx");
        orderInfoExportExcel(response, getExcelOrderInfoList(processInfoParam));
    }


    public static void orderInfoExportExcel(HttpServletResponse response, List<ExcelOrderInfo> paramList) throws IOException {
        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).build();
        WriteSheet writeSheet = EasyExcel.writerSheet(0, "sheet").head(ExcelOrderInfo.class).build();
        excelWriter.write(paramList, writeSheet);
        excelWriter.finish();
    }

    @Override
    public void exportOrderDetail(HttpServletResponse response, String productProduceProcessId) throws IOException {
        //List<Map<String,Object>> list=getPurOrderDetail(productProduceProcessId);
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment; filename" + "param.xlsx");
        exportExcel(response, getExportOrderDetail(productProduceProcessId));
    }

    private List<ProductProduceProcessDetail> getExportOrderDetail(String productProduceProcessId) {
        List<ProductProduceProcessDetail> list = new ArrayList<>();
        List<Map<String, Object>> mlist = getPurOrderDetail(productProduceProcessId);
        for (Map map : mlist) {
            ProductProduceProcessDetail productProduceProcessDetail = new ProductProduceProcessDetail();
            if (map.get("aaDate") != null) {
                productProduceProcessDetail.setActualAssemblyStartDate(map.get("aaDate").toString());
            }
            if (map.get("asDate") != null) {
                productProduceProcessDetail.setActualProduceStartDate(map.get("asDate").toString());
            }
            if (map.get("apsDate") != null) {
                productProduceProcessDetail.setActualProductStockInDate(map.get("apsDate").toString());
            }
            if (map.get("aqsDtae") != null) {
                productProduceProcessDetail.setActualQltStartDate(map.get("aqsDtae").toString());
            }
            productProduceProcessDetail.setAssemblyQty(map.get("assQty").toString());
            productProduceProcessDetail.setAssemblySatisfy(map.get("assSat").toString());
            productProduceProcessDetail.setNoAssemblyQty(map.get("noAssQty").toString());
            if (map.get("planAssDate") != null) {
                productProduceProcessDetail.setPlanAssemblyDate(map.get("planAssDate").toString());
            }
            if (map.get("ppDate") != null) {
                productProduceProcessDetail.setPlanProductStockInDate(map.get("ppDate").toString());
            }
            if (map.get("psDate") != null) {
                productProduceProcessDetail.setPlanQltStartDate(map.get("psDate").toString());
            }
            if (map.get("planDate") != null) {
                productProduceProcessDetail.setPlanStartDate(map.get("planDate").toString());
            }
            productProduceProcessDetail.setProProductPlanCode(map.get("planCode").toString());
            productProduceProcessDetail.setSaleOrderManageNo(map.get("orderNo").toString());
            list.add(productProduceProcessDetail);
        }
        return list;
    }

    public static void exportExcel(HttpServletResponse response, List<ProductProduceProcessDetail> paramList) throws IOException {
        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).build();
        WriteSheet writeSheet = EasyExcel.writerSheet(0, "sheet").head(ProductProduceProcessDetail.class).build();
        excelWriter.write(paramList, writeSheet);
        excelWriter.finish();
    }

    @Override
    public void exportStockReport(HttpServletResponse response, StockReportParam stockReportParam) throws IOException {
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment; filename" + "param.xlsx");
        stockExportExcel(response, getExcelStockReportList(stockReportParam));
    }

    public static void stockExportExcel(HttpServletResponse response, List<ExcelStockReport> paramList) throws IOException {
        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).build();
        WriteSheet writeSheet = EasyExcel.writerSheet(0, "sheet").head(ExcelStockReport.class).build();
        excelWriter.write(paramList, writeSheet);
        excelWriter.finish();
    }

    public List<ExcelStockReport> getExcelStockReportList(StockReportParam stockReportParam) {
        List<ExcelStockReport> list = new ArrayList<>();
        List<Map<String, Object>> mlist = getStockReportList(stockReportParam);
        for (Map map : mlist) {
            ExcelStockReport excelStockReport = new ExcelStockReport();
            excelStockReport.setSupProductNo(map.get("supProductNo").toString());
            excelStockReport.setUnit(map.get("unit").toString());
            excelStockReport.setCustName((String) map.get("custName"));
            excelStockReport.setMatCode((String) map.get("matCode"));
            excelStockReport.setMatName((String) map.get("matName"));
            excelStockReport.setDrawNo((String) map.get("drawNo"));
            excelStockReport.setNeedQty(map.get("needQty").toString());
            excelStockReport.setStockQty(map.get("stockQty").toString());
            excelStockReport.setStockType((String) map.get("stockType"));
            excelStockReport.setPurChannel((String) map.get("purChannel"));
            list.add(excelStockReport);
        }
        return list;
    }

    @Override
    public void exportProductQltReport(HttpServletResponse response, ProductQltReportParam productQltReportParam) throws ParseException, IOException {
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment; filename" + "param.xlsx");
        qltExportExcel(response, getExcelProductQltReportList(productQltReportParam));
    }

    public static void qltExportExcel(HttpServletResponse response, List<ExcelProductQltReport> paramList) throws IOException {
        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).build();
        WriteSheet writeSheet = EasyExcel.writerSheet(0, "sheet").head(ExcelProductQltReport.class).build();
        excelWriter.write(paramList, writeSheet);
        excelWriter.finish();
    }

    public List<ExcelProductQltReport> getExcelProductQltReportList(ProductQltReportParam productQltReportParam) throws ParseException {
        List<ExcelProductQltReport> list = new ArrayList<>();
        List<Map<String, Object>> mlist = getProductQltReportList(productQltReportParam);
        for (Map map : mlist) {
            ExcelProductQltReport excelProductQltReport = new ExcelProductQltReport();
            excelProductQltReport.setCustName((String) map.get("supplier"));
            excelProductQltReport.setMatCode((String) map.get("matCode"));
            excelProductQltReport.setMatName((String) map.get("matName"));
            excelProductQltReport.setDrawNo((String) map.get("drawNo"));
            excelProductQltReport.setPurOrderNo((String) map.get("purOrderNo"));
            excelProductQltReport.setMatDesc((String) map.get("matDesc"));
            excelProductQltReport.setSerialNo((String) map.get("serialNo"));
            if (map.get("stockDate") != null) {
                excelProductQltReport.setStockDate(map.get("stockDate").toString());
            }
            excelProductQltReport.setQltResult((String) map.get("qltResult"));
            excelProductQltReport.setAssNum(map.get("assNum").toString());
            list.add(excelProductQltReport);
        }
        return list;
    }

    @Override
    public void exportMatTechnologyQltReport(HttpServletResponse response, String pqId, String isVideo) throws IOException {
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment; filename" + "param.xlsx");
        technologyExportExcel(response, getExcelProductQltReportList(pqId, isVideo));
    }

    public static void technologyExportExcel(HttpServletResponse response, List<ExcelMatTechnologyQltReport> paramList) throws IOException {
        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).build();
        WriteSheet writeSheet = EasyExcel.writerSheet(0, "sheet").head(ExcelMatTechnologyQltReport.class).build();
        excelWriter.write(paramList, writeSheet);
        excelWriter.finish();
    }

    public List<ExcelMatTechnologyQltReport> getExcelProductQltReportList(String pqId, String isVideo) {
        List<ExcelMatTechnologyQltReport> list = new ArrayList<>();
        List<Map<String, Object>> mlist = getMatTechnologyQltReportList(pqId, isVideo);
        for (Map map : mlist) {
            ExcelMatTechnologyQltReport excelMatTechnologyQltReport = new ExcelMatTechnologyQltReport();
            excelMatTechnologyQltReport.setStName(map.get("stName").toString());
            excelMatTechnologyQltReport.setUnit((String) map.get("unit"));
            excelMatTechnologyQltReport.setPositive(map.get("positive").toString());
            excelMatTechnologyQltReport.setNegative(map.get("negative").toString());
            excelMatTechnologyQltReport.setInspector((String) map.get("inspector"));
            excelMatTechnologyQltReport.setQltResult((String) map.get("qltResult"));
            if (map.get("qltDate") != null) {
                excelMatTechnologyQltReport.setQltDate(map.get("qltDate").toString());
            }
            excelMatTechnologyQltReport.setActualValue((String) map.get("actualValue"));
            list.add(excelMatTechnologyQltReport);
        }
        return list;
    }

    @Override
    public void exportTechnologyReport(HttpServletResponse response, TechnologyReportParam technologyReportParam) throws IOException {
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment; filename" + "param.xlsx");
        exportExcel1(response, getExcelTechnologyReportList(technologyReportParam));
    }

    public static void exportExcel1(HttpServletResponse response, List<ExcelTechnologyReport> paramList) throws IOException {
        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).build();
        WriteSheet writeSheet = EasyExcel.writerSheet(0, "sheet").head(ExcelTechnologyReport.class).build();
        excelWriter.write(paramList, writeSheet);
        excelWriter.finish();
    }

    public List<ExcelTechnologyReport> getExcelTechnologyReportList(TechnologyReportParam technologyReportParam) {
        List<ExcelTechnologyReport> list = new ArrayList<>();
        List<Map<String, Object>> mlist = getTechnologyReportList(technologyReportParam);
        for (Map map : mlist) {
            ExcelTechnologyReport excelTechnologyReport = new ExcelTechnologyReport();
            excelTechnologyReport.setMatCode((String) map.get("matCode"));
            excelTechnologyReport.setDrawNo((String) map.get("drawNo"));
            excelTechnologyReport.setMatName((String) map.get("matName"));
            excelTechnologyReport.setSerialNo((String) map.get("serialNo"));
            excelTechnologyReport.setTName((String) map.get("tName"));
            excelTechnologyReport.setInName((String) map.get("inName"));
            excelTechnologyReport.setUnit((String) map.get("unit"));
            excelTechnologyReport.setPositive(map.get("positive").toString());
            excelTechnologyReport.setNegative(map.get("negative").toString());
            excelTechnologyReport.setActual((String) map.get("actual"));
            if (map.get("qltDate") != null) {
                excelTechnologyReport.setQltDate(map.get("qltDate").toString());
            }
            excelTechnologyReport.setInspector((String) map.get("inspector"));
            excelTechnologyReport.setQltResult((String) map.get("qltResult"));
            list.add(excelTechnologyReport);
        }
        return list;
    }

    @Override
    public List<Map<String, Object>> listDataType() {
        return orderInfoMapper.listDataType();
    }

    @Override
    public void saveOrderInfo(OrderGoodsInfoParam orderInfoParam) {
        orderInfoMapper.saveOrderInfo(orderInfoParam);
    }

    /**
     * 获取买家用户所有实物订单和服务订单的状态
     *
     * @param createUser
     */
    @Override
    @DoPage
    public List<OrderStateVO> getOrderSate(String createUser) {
        return orderInfoMapper.getOrderSate("079231fdcf6c46d99b4221e892de3cba");
    }

    /**
     * 根据买家用户id获取其订单
     *
     * @return
     */
    @Override
    @DoPage
    public List<OrderStateVO> getOrderByUserId(String orderId) {
        return orderInfoMapper.getOrderByUserId(UserSession.getUserId(), orderId);
    }

    /**
     * 获取店铺订单列表
     *
     * @param orderInfoVO
     * @return
     */
    @Override
    @DoPage
    public List<OrderInfo> getShopOrderList(OrderInfoVO orderInfoVO) {
        return orderInfoMapper.selectShopOrderList(orderInfoVO, UserSession.getUserId());
    }

    /**
     * 根据店铺ID获取店铺下的所有订单
     * 包括订单状态和时间的搜索
     *
     * @param orderInfoMO
     * @return
     */
    @Override
    @DoPage
    public List<OrderInfoMO> getOrderInfoByCsDbId(OrderInfoMO orderInfoMO) {
        return orderInfoMapper.selectOrderInfoByCsDbId(orderInfoMO);
    }

    /**
     * 重新生成服务订单
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void reAddOrderService(OrderServiceVO orderServiceVO) {
        String orderServiceId = orderServiceVO.getServiceOrderId();
        String type = orderServiceVO.getType();
        OrderInfoVO orderInfoVO = new OrderInfoVO();

        //服务分类的标志位
        Map<String, Integer> flagMap = new HashMap<>(12);
        flagMap.put("fwfl005", 0);
        flagMap.put("fwfl006", 1);
        flagMap.put("fwfl007", 0);
        flagMap.put("fwfl008", 0);
        flagMap.put("fwfl009", 0);
        flagMap.put("fwfl010", 0);
        flagMap.put("fwfl011", 1);
        flagMap.put("fwfl012", 1);
        flagMap.put("fwfl013", 1);
        flagMap.put("fwfl016", 0);
        flagMap.put("fwfl017", 0);
        flagMap.put("fwfl018", 0);

        //主订单

        //发货地址

        PurchaseToProjectRedisMO purchaseToProjectRedisMO = projectService.getPurchaseToProjectFromRedis(orderInfoVO.getPlanPurchaseId());

//        UserInfoToRedisMO userInfoToRedisMO = new UserInfoToRedisMO();
        UserInfoToRedisMO userInfoToRedisMO = sysUserService.getUserInfoFromRedis(UserSession.getUserId());
        String userPhone = "";
        if (userInfoToRedisMO != null) {
            userPhone = userInfoToRedisMO.getUserMobile();
            orderInfoVO.setOrderUserCode(userInfoToRedisMO.getUciDbid());
        }
        //结算点

        //订单中实物商品list


        //生成采购服务订单
        if (type.equals("2")) {
            OrderServicePurchase orderServicePurchase = orderServicePurchaseMapper.selectById(orderServiceId);
            String orderId = orderServicePurchase.getOrderId();
            String oldServiceId = orderServicePurchase.getOspId();
            OrderInfo orderInfo = orderInfoMapper.selectById(orderId);
            BeanUtils.copyProperties(orderInfo, orderInfoVO);
            List<OrderGoods> orderGoodsList = orderGoodsMapper.getByOrderId(orderId);
            orderInfoVO.setOrderGoodsList(orderGoodsList);
            orderInfoVO.setOrderServicePurchaseVO(orderServiceVO.getOrderServicePurchaseVO());
            OrderServicePurchaseVO orderServicePurchaseVO = addOrderServicePurchase(orderInfoVO, orderId, userPhone);
            orderInfoVO.setOrderServicePurchaseVO(orderServicePurchaseVO);

            orderInfoMapper.batchInsertServicePurchaseGoods(orderServicePurchaseVO.getOrderServicePurchaseGoodsList());
            orderServicePurchaseMapper.insert(orderInfoVO.getOrderServicePurchaseVO());
            orderServicePurchaseMapper.deleteById(oldServiceId);
            orderServicePurchaseGoodsMapper.deleteByServiceId(oldServiceId);
        }
        //生成配送服务订单
        if (type.equals("4")) {
            OrderServiceTransport orderServiceTransport = orderServiceTransportMapper.selectById(orderServiceId);
            String orderId = orderServiceTransport.getOrderId();
            String oldServiceId = orderServiceTransport.getOstId();
            OrderInfo orderInfo = orderInfoMapper.selectById(orderId);
            BeanUtils.copyProperties(orderInfo, orderInfoVO);
            List<OrderGoods> orderGoodsList = orderGoodsMapper.getByOrderId(orderId);
            orderInfoVO.setOrderGoodsList(orderGoodsList);
            orderInfoVO.setOrderServiceTransportVO(orderServiceVO.getOrderServiceTransportVO());
            OrderServiceTransportVO orderServiceTransportVO = addOrderServiceTransport(orderInfoVO, orderId, userPhone, flagMap);
            orderInfoVO.setOrderServiceTransportVO(orderServiceTransportVO);
            orderInfoMapper.batchInsertServiceTransportGoods(orderServiceTransportVO.getOrderServiceTransportGoodsList());
            orderServiceTransportMapper.insert(orderInfoVO.getOrderServiceTransportVO());
            orderServiceTransportMapper.deleteById(oldServiceId);
            orderServiceTransportGoodsMapper.deleteByServiceId(oldServiceId);
        }
        //生成质控服务订单
        if (type.equals("3")) {
            OrderServiceQuality orderServiceQuality = orderServiceQualityMapper.selectById(orderServiceId);
            String orderId = orderServiceQuality.getOrderId();
            String oldServiceId = orderServiceQuality.getOsqId();
            OrderInfo orderInfo = orderInfoMapper.selectById(orderId);
            BeanUtils.copyProperties(orderInfo, orderInfoVO);
            List<OrderGoods> orderGoodsList = orderGoodsMapper.getByOrderId(orderId);
            orderInfoVO.setOrderGoodsList(orderGoodsList);
            orderInfoVO.setOrderServiceQualityVOList(orderServiceVO.getOrderServiceQualityVOList());
            List<OrderServiceQualityVO> orderServiceQualityVOList = addOrderServiceQuality(orderInfoVO, orderId, userPhone, flagMap);
            orderInfoVO.setOrderServiceQualityVOList(orderServiceQualityVOList);

            orderInfoMapper.batchInsertServiceQualityGoods(orderServiceQualityVOList.get(0).getOrderServiceQualityGoodsList());
            orderServiceQualityMapper.insert(orderInfoVO.getOrderServiceQualityVOList().get(0));
            orderServiceQualityMapper.deleteById(oldServiceId);
            orderServiceQualityGoodsMapper.deleteByServiceId(oldServiceId);
        }
        //生成仓储服务订单
        if (type.equals("5")) {
            OrderServiceStorage orderServiceStorage = orderServiceStorageMapper.selectById(orderServiceId);
            String orderId = orderServiceStorage.getOrderId();
            String oldServiceId = orderServiceStorage.getOssId();
            OrderInfo orderInfo = orderInfoMapper.selectById(orderId);
            BeanUtils.copyProperties(orderInfo, orderInfoVO);
            List<OrderGoods> orderGoodsList = orderGoodsMapper.getByOrderId(orderId);
            orderInfoVO.setOrderGoodsList(orderGoodsList);
            orderInfoVO.setOrderServiceStorageVOList(orderServiceVO.getOrderServiceStorageVOList());
            List<OrderServiceStorageVO> orderServiceStorageVOList = addOrderServiceStorage(orderInfoVO, orderId, userPhone, flagMap);
            orderInfoVO.setOrderServiceStorageVOList(orderServiceStorageVOList);

            orderInfoMapper.batchInsertServiceStorageGoods(orderServiceStorageVOList.get(0).getOrderServiceStorageGoodsList());
            orderServiceStorageMapper.insert(orderInfoVO.getOrderServiceStorageVOList().get(0));
            orderServiceStorageMapper.deleteById(oldServiceId);
            orderServiceStorageGoodsMapper.deleteByServiceId(oldServiceId);
        }
        //生成结算服务订单
        if (type.equals("6")) {
            OrderServiceSettle orderServiceSettle = orderServiceSettleMapper.selectById(orderServiceId);
            String orderId = orderServiceSettle.getOrderId();
            String oldoldServiceId = orderServiceSettle.getOsseId();
            OrderInfo orderInfo = orderInfoMapper.selectById(orderId);
            BeanUtils.copyProperties(orderInfo, orderInfoVO);
            List<OrderGoods> orderGoodsList = orderGoodsMapper.getByOrderId(orderId);
            orderInfoVO.setOrderGoodsList(orderGoodsList);
            orderInfoVO.setOrderServiceSettleVO(orderServiceVO.getOrderServiceSettleVO());
            OrderServiceSettleVO orderServiceSettleVO = addOrderServiceSettle(orderInfoVO, orderId, userPhone, purchaseToProjectRedisMO);
            orderInfoVO.setOrderServiceSettleVO(orderServiceSettleVO);

//            OrderServiceSettleVO orderServiceSettleVO = orderServiceVO.getOrderServiceSettleVO();
//            BeanUtils.copyProperties(addOrderServiceSettle(orderInfoVO, orderId, userPhone, purchaseToProjectRedisMO),orderServiceSettleVO);
            orderInfoMapper.batchInsertServiceSettleGoods(orderServiceSettleVO.getOrderServiceSettleGoodsList());
            orderServiceSettleMapper.insert(orderServiceSettleVO);
            orderServiceSettleMapper.deleteById(oldoldServiceId);
            orderServiceSettleGoodsMapper.deleteByServiceId(oldoldServiceId);
        }
    }

    @Override
    public Map<String, Object> updateOrderStatus(Map<String, Object> map) {
        if (map == null) {
            return ResponseUtil.toWarningMessage("数据为空", new HashMap<>());
        }
        try {
            String orderNo = map.get("orderNo").toString();
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("ORDER_ID", orderNo);
            OrderInfo orderInfo = orderInfoMapper.selectOne(queryWrapper);
            if (orderInfo == null) {
                throw new RuntimeException("订单不存在");
            }
            orderInfo.setOrderState(String.valueOf(map.get("auditStatus")));
            orderInfo.setUpdateTime(new Date());
            orderInfo.setUpdateUser(UserSession.getUserId());
            orderInfoMapper.updateById(orderInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseUtil.toWarningMessage("修改失败", false);
        }
        return ResponseUtil.toSuccessMessage("修改成功", map);
    }

    @Override
    public List<Map<String, Object>> getOrderInfoByUserId(String userId) {
        return orderInfoMapper.getOrderInfoByUserId(userId);
    }

    @Override
    public List<Map<String, Object>> getServiceOrderInfoByUser(String userId, String shopType) {
        List<Map<String, Object>> serviceInfo = new ArrayList<>();
        if ("2".equals(shopType)) {
            serviceInfo.addAll(orderInfoMapper.getPurchaseOrderInfo(userId, shopType));
        } else if ("4".equals(shopType)) {
            serviceInfo.addAll(orderInfoMapper.getTransportOrderInfo(userId, shopType));
        } else if ("3".equals(shopType)) {
            serviceInfo.addAll(orderInfoMapper.getQualityOrderInfo(userId, shopType));
        } else if ("5".equals(shopType)) {
            serviceInfo.addAll(orderInfoMapper.getStorageOrderInfo(userId, shopType));
        } else if ("6".equals(shopType)) {
            serviceInfo.addAll(orderInfoMapper.getSettleOrderInfo(userId, shopType));
        }
        return serviceInfo;
    }

    @Override
    public String getMatCodeByGoodsId(String goodsDbid) {
        return orderInfoMapper.getMatCodeByGoodsId(goodsDbid);
    }
}
